每次测试的Jest Mock模块 [英] Jest Mock module per test

查看:714
本文介绍了每次测试的Jest Mock模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Jest中的嘲笑(如何对实现进行单元测试)感到困惑.问题是我想嘲笑不同的预期行为.

I am quite confused with mocking in Jest an how to unit test the implementations. The thing is i want to mock different expected behaviours.

有什么办法可以做到这一点?因为导入只能位于文件的顶部,并且为了能够模拟某些内容,因此必须在导入之前声明它.我还尝试过传递本地函数,以便覆盖行为,但开玩笑地抱怨您不允许传递任何本地函数.

Is there any way to achieve this? as imports can be only on the top of the file and to be able to mock something it must be declared before the import. I have also tried to pass a local function so I could overwrite the behaviour but jest complains you are not allowed to pass anything local.

jest.mock('the-package-to-mock', () => ({
  methodToMock: jest.fn(() => console.log('Hello'))
}));

import * as theThingToTest from '../../../app/actions/toTest'
import * as types from '../../../app/actions/types'

it('test1', () => {
  expect(theThingToTest.someAction().type).toBe(types.SOME_TYPE)
})

it('test2', () => {
  //the-package-to-mock.methodToMock should behave like something else
  expect(theThingToTest.someAction().type).toBe(types.SOME_TYPE)
})

可以想象

内部是theThingToTest.someAction()使用the-package-to-mock.methodToMock

推荐答案

您可以使用间谍程序进行模拟并导入模拟的模块.在测试中,您可以使用 mockImplementation :

You can mock with a spy and import the mocked module. In your test you set how the mock should behave using mockImplementation:

jest.mock('the-package-to-mock', () => ({
  methodToMock: jest.fn()
}));
import {methodToMock} from 'the-package-to-mock'

it('test1', () => {
  methodToMock.mockImplementation(() => 'someValue')
})

it('test2', () => {
   methodToMock.mockImplementation(() => 'anotherValue')
})

这篇关于每次测试的Jest Mock模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆