Javascript Jest-一个函数模拟多个测试文件的文件
我想要这样的东西:Javascript Jest-一个函数模拟多个测试文件的文件,javascript,reactjs,jestjs,react-testing-library,Javascript,Reactjs,Jestjs,React Testing Library,我想要这样的东西: mockFunctions.ts jest.mock('../utils', () => { return { getNumbers: () => [1,2,3] } }) ---import from mockFunctions--- ... it('After adding another number array has more elements', () => { const numbers = <get these
mockFunctions.ts
jest.mock('../utils', () => {
return {
getNumbers: () => [1,2,3]
}
})
---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);
})
---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);
})
\uuuu测试/test1.ts
jest.mock('../utils', () => {
return {
getNumbers: () => [1,2,3]
}
})
---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);
})
---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);
})
是否可以在一个文件中实现模拟函数,然后将其导入多个测试文件中?有一些替代方法可以实现这一点:
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
目录。看export const getNumbers= () => [1, 2, 3, 4, 5];
->utils/\uuuu mocks\uuuu
/index.js
export const getNumbers= () => [3, 4];
jest.config.js
{
"setupFilesAfterEnv": [
"<rootDir>/jestSetup.js"
]
}
{
"setupFilesAfterEnv": [
"<rootDir>/jestSetup.js"
]
}
{
"setupFilesAfterEnv": [
"<rootDir>/jestSetup.js"
]
}
{
"setupFilesAfterEnv": [
"<rootDir>/jestSetup.js"
]
}
或者用mock创建一个文件
mocks.js
jest.mock("../utils", () => ({
getNumbers: () => [3, 4]
}));
jestSetup.js
jest.mock("../utils"); // will apply to all tests
jest.mock("../utils", () => ({
getNumbers: () => [3, 4]
}));
import './mocks.js'
如果不想在特定测试中使用模拟,可以调用:
jest.unmock('../utils')
请参阅:您好,您可以在函数中定义mock,然后在需要的地方调用该函数。@lissettdm您能给我一个例子吗?可重用mock就是
\uuumocks\uuuu
的用途。你试过了吗?我想再进一步,我可以在同一个测试目录中使用另外两个模拟吗?例如,两个文件使用一个文件中的模拟,另外两个文件使用第二个文件中的模拟。我还没有在你附在这个答案上的网页上找到它,这个答案只能为所有测试提供一个端点实现。你能在你有这个场景的地方附加一个链接吗?这样我才能更清楚地理解它?