3 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
我已經(jīng)能夠通過使用涉及到的黑客解決此問題import *。它甚至適用于命名和默認(rèn)導(dǎo)出!
對(duì)于命名出口:
// dependency.js
export const doSomething = (y) => console.log(y)
// myModule.js
import { doSomething } from './dependency';
export default (x) => {
doSomething(x * 2);
}
// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';
describe('myModule', () => {
it('calls the dependency with double the input', () => {
dependency.doSomething = jest.fn(); // Mutate the named export
myModule(2);
expect(dependency.doSomething).toBeCalledWith(4);
});
});
或默認(rèn)導(dǎo)出:
// dependency.js
export default (y) => console.log(y)
// myModule.js
import dependency from './dependency'; // Note lack of curlies
export default (x) => {
dependency(x * 2);
}
// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';
describe('myModule', () => {
it('calls the dependency with double the input', () => {
dependency.default = jest.fn(); // Mutate the default export
myModule(2);
expect(dependency.default).toBeCalledWith(4); // Assert against the default
});
});
正如Mihai Damian在下面正確指出的那樣,這是對(duì)的模塊對(duì)象進(jìn)行了變異dependency,因此它將“泄漏”到其他測試中。因此,如果使用這種方法,則應(yīng)存儲(chǔ)原始值,然后在每次測試后再次將其重新設(shè)置。要使用Jest輕松實(shí)現(xiàn)此目的,請(qǐng)使用spyOn()方法代替,jest.fn()因?yàn)樗С州p松恢復(fù)其原始值,因此避免了前面提到的“泄漏”。

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超13個(gè)贊
您必須模擬模塊并自己設(shè)置間諜:
import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency', () => ({
doSomething: jest.fn()
}))
describe('myModule', () => {
it('calls the dependency with double the input', () => {
myModule(2);
expect(dependency.doSomething).toBeCalledWith(4);
});
});
添加回答
舉報(bào)