[英]Jest - one function mocks file for multiple test files
我想要這樣的東西:
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__
目錄。 見https://jestjs.io/docs/en/manual-mocks實用程序/ index.js
export const getNumbers= () => [1, 2, 3, 4, 5];
->utils/ __mocks__
/index.js
export const getNumbers= () => [3, 4];
開玩笑的配置文件
{
"setupFilesAfterEnv": [
"<rootDir>/jestSetup.js"
]
}
jestSetup.js
jest.mock("../utils"); // will apply to all tests
開玩笑的配置文件
{
"setupFilesAfterEnv": [
"<rootDir>/jestSetup.js"
]
}
jestSetup.js
jest.mock("../utils", () => ({
getNumbers: () => [3, 4]
}));
或者用模擬創建一個文件
模擬.js
jest.mock("../utils", () => ({
getNumbers: () => [3, 4]
}));
jestSetup.js
import './mocks.js'
如果您不想在特定測試中使用模擬,您可以調用:
jest.unmock('../utils')
請參閱: https : //jestjs.io/docs/en/jest-object#jestunmockmodulename
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.