我想要这样的东西:
mockFunctions.ts
jest.mock('../utils', () => {
return {
getNumbers: () => [1,2,3]
}
})
__tests__/test1.ts
---import from mockFunctions---
...
it('After adding another number array has more elements', () => {
const numbers = <get these numbers using mock function>
expect([...numbers, 11]).toHaveLength(4);
})
__tests__/test2.ts
---import from mockFunctions---
...
it('After removing a number, array has less elements', () => {
const numbers = <get these numbers using mock function>
expect(numbers.filter(x => x>1)).toHaveLength(2);
})
是否可以有一个文件实现了模拟功能,然后将它们导入多个测试文件中?
有一些替代方法可以实现此目的:
__mocks__
在utils文件夹中添加目录。参见https://jestjs.io/docs/en/manual-mocksutils / index.js
export const getNumbers= () => [1, 2, 3, 4, 5];
->实用程序/ __mocks__
/index.js
export const getNumbers= () => [3, 4];
is.config.js
{
"setupFilesAfterEnv": [
"<rootDir>/jestSetup.js"
]
}
jestSetup.js
jest.mock("../utils"); // will apply to all tests
is.config.js
{
"setupFilesAfterEnv": [
"<rootDir>/jestSetup.js"
]
}
jestSetup.js
jest.mock("../utils", () => ({
getNumbers: () => [3, 4]
}));
或使用模拟文件创建文件
模拟
jest.mock("../utils", () => ({
getNumbers: () => [3, 4]
}));
jestSetup.js
import './mocks.js'
如果您不想在特定测试中使用模拟,则可以调用:
jest.unmock('../utils')
参见:https : //jestjs.io/docs/en/jest-object#jestunmockmodulename
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句