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

查看:30
本文介绍了每次测试的 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

internally as you can imagine theThingToTest.someAction() uses the-package-to-mock.methodToMock

推荐答案

您可以使用 spy 进行模拟并导入模拟的模块.在您的测试中,您使用 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天全站免登陆