javascript - Jest spyOn 不是类或对象类型的函数

标签 javascript jasmine jestjs

我熟悉在类或对象方法上设置 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/

相关文章:

javascript - 从 TCP 流中解析出数据段

javascript - 如何使用 AJAX 打印出 div 中的数据?

javascript - Node js,process.env 不读取环境变量

javascript - Jasmine spy 调用的问题

javascript - 尝试为每一行编写测试用例

jasmine - 如何使用 jasmine 2.0 从命令行运行单个测试

javascript - 开 Jest : Add component children elements to snapshot

javascript - 从 Angular Controller 访问字典

javascript - 类型错误 : Cannot read property 'cwd' of undefined

angular - 语法错误: Cannot use import statement outside a module using @ionic-native/health in Angular/Nx/jest app