我熟悉在类或对象方法上设置 spy ,但是当函数只是一个导出默认值时怎么办 - 这样方法本身是独立的,就像一个实用程序一样?
我有一些现有的代码,如下所示:
const Funct1 = props => {
if(props){
Funct2(args);
}
// or return something
};
const Funct2 = props => {
// do something
return true
};
export default Funct1; //Yes the existing export is named the same as the "entry" method above.
例如,我想监视
Funct1
接到电话和Funct2
返回真。import Funct1 from "../../../src/components/Funct1";
describe("Test the Thing", () => {
it("New Test", () => {
let props = {
active: true,
agentStatus: "online"
};
const spy = spyOn(Funct2, "method name"); <-- how doe this work if not an obj or class?
Funct1(props);
//If I try Funct2(props) instead, terminal output is "Funct2 is not defined"
expect(spy).toHaveBeenCalledWith(props);
});
});
最佳答案
我不是 Jest 专家,但我的建议是:
1)当函数默认导出时,我使用类似:
import Funct1 from "../../../src/components/Funct1";
...
jest.mock("../../../src/components/Funct1");
...
expect(Funct1).toHaveBeenCalledWith(params);
2)当模块(utils.js)有多个导出为
export const f1 = () => {};
...
export const f8 = () => {};
你可以试试
import * as Utils from "../../../src/components/utils"
const f8Spy = jest.spyOn(Utils, 'f8');
...
expect(f8Spy).toHaveBeenCalledWith(params);
Similar discussion here
关于javascript - Jest spyOn 不是类或对象类型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49457451/