jest.mock() 在测试内部不起作用,仅在测试外部起作用

k-w*_*ski 36 reactjs jestjs

我有一套简单的测试,在某些情况下我想模拟一个模块,而在某些情况下则不想。但是,jest.mock()只有在测试之外才有效。任何人都知道为什么会这样以及我做错了什么?

这是我想要模拟的函数的实际导入

import {hasSupport, getCallingCode} from 'utils/countryCallingCode';
Run Code Online (Sandbox Code Playgroud)

这是这个函数的模拟:

jest.mock('utils/countryCallingCode', () => ({
    getCallingCode: () => '1',
    hasSupport: () => true,
  }));
Run Code Online (Sandbox Code Playgroud)

现在,工作场景是:

//imports
//mock

describe('...', () -> {
    it('...', () -> {

    });
});
Run Code Online (Sandbox Code Playgroud)

这不起作用:

//imports

describe('...', () -> {
    //mock

    it('...', () -> {

    });
});
Run Code Online (Sandbox Code Playgroud)

这也不起作用:

//imports

describe('...', () -> {
    it('...', () -> {
        //mock
    });
});
Run Code Online (Sandbox Code Playgroud)

Mat*_*abe 9

使用mockReturnValue(...)

import {
  getCallingCode,
  hasSupport,
} from 'utils/countryCallingCode'

jest.mock('utils/countryCallingCode', () => ({
  getCallingCode: jest.fn(),
  hasSupport: jest.fn(),
}))

describe('...', () => {
    it('...', () => {
        getCallingCode.mockReturnValue(1)
        hasSupport.mockReturnValue(false)

        expect(...
    })

    it('...', () => {
        getCallingCode.mockReturnValue(0)
        hasSupport.mockReturnValue(true)

        expect(...
    })
})

Run Code Online (Sandbox Code Playgroud)

处理该实用程序的默认导出:

import theUtil from 'utils/theUtil'

jest.mock('utils/theUtil', () => ({
  __esModule: true,
  default: jest.fn(),
}))

describe('...', () => {
    it('...', () => {
        theUtil.mockReturnValue('some value')

        expect(...
    })

    it('...', () => {
        theUtil.mockReturnValue('some other value')

        expect(...
    })
})
Run Code Online (Sandbox Code Playgroud)

打字稿:

使用as jest.Mock。例如:

...
(getCallingCode as jest.Mock).mockReturnValue(1)
...
(theUtil as jest.Mock).mockReturnValue('some value')
...
Run Code Online (Sandbox Code Playgroud)

或者,更干净地说:

import theUtil from 'utils/theUtil'

jest.mock('utils/theUtil', () => ({
  __esModule: true,
  default: jest.fn(),
}))
const mockTheUtil = theUtil as jest.Mock

describe('...', () => {
    it('...', () => {
        mockTheUtil.mockReturnValue('some value')

        expect(...
    })
})
Run Code Online (Sandbox Code Playgroud)


Dea*_*mes 7

Jest 会自动将jest.mockES 模块中的调用提升到文件顶部,位于任何 import 语句之前。这样做是为了允许树中的其他模块使用模拟模块。

Jest文档还提供了一个示例存储库来解释Jest 模拟的工作原理

如果你想阻止这种自动行为,你可以使用jest.dontMock

  • 如果文档没有按照其说明应为您执行的操作,您可能需要设置一个可重现的沙箱示例。 (2认同)