main.js
import { a } from './a.js';
const { output } = a();
const c = num => num + output.b();
export { c }
a.js
const a = () => ({
output: { b: () => 5 }, // I want to mock this function
});
export { a }
main.test.js
import { c } from './main.js';
describe('main file', () => {
test("c function", () => {
const result = c(4);
expect(result).toBe(9);
});
})
如何模拟output.b
函数?
解决方案1
main.test.js:
import { c } from './main.js';
jest.mock('./a.js', () => ({
a: () => ({
output: { b: jest.fn(() => 15) }, // adding a mock function
}),
}));
describe('main file', () => {
test("c function", () => {
const result = c(4);
expect(result).toBe(19);
});
})
解决方案2
__mocks_/a.js:
const a = () => ({
output: { b: jest.fn(() => 15) },
});
export { a }
main.test.js:
import { c } from './main.js';
jest.mock('./a.js');
describe('main file', () => {
test("c function", () => {
const result = c(4);
expect(result).toBe(19);
});
})