Jest spyOn 不是 Class 或 Object 类型的函数

Phi*_*cks 13 javascript jasmine jestjs

我熟悉在 Class 或 Object 方法上设置间谍,但是当函数只是一个导出默认值时怎么办 - 这样方法本身是独立的,就像一个实用程序?

我有一些现有的代码,如下所示:

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.
Run Code Online (Sandbox Code Playgroud)

而且,例如,我想监视Funct1被调用并Funct2返回 true。

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);
    });
});
Run Code Online (Sandbox Code Playgroud)

Дми*_*нов 16

I am not expert in jest, but my recommendation to think about:

1) When the function is exported as default I use something like:

import Funct1 from "../../../src/components/Funct1";
...
jest.mock("../../../src/components/Funct1");
...
expect(Funct1).toHaveBeenCalledWith(params);
Run Code Online (Sandbox Code Playgroud)

2) When the module (utils.js) has multiple exports as

export const f1 = () => {};
...
export const f8 = () => {};
Run Code Online (Sandbox Code Playgroud)

You can try

import * as Utils from "../../../src/components/utils"
const f8Spy = jest.spyOn(Utils, 'f8');
...
expect(f8Spy).toHaveBeenCalledWith(params);
Run Code Online (Sandbox Code Playgroud)

Similar discussion here


小智 11

用 包裹你的函数jest.fn。像这样:

const simpleFn = (arg) => arg;
const simpleFnSpy = jest.fn(simpleFn);
simpleFnSpy(1);
expect(simpleFnSpy).toBeCalledWith(1); // Passes test
Run Code Online (Sandbox Code Playgroud)


小智 -5

我相信在不修改现有代码的情况下不可能测试 Funct1 调用 Funct2 。如果后者是一个选项,那么这里有两个引入依赖注入的选项:

  • 创建并导出工厂函数:

    const Funct2 = props => {
        // do something
        return true;
    };
    const Funct1 = CreateFunct1(Funct2);
    export function CreateFunct1(Funct2) {
        return props => {
            if (props) {
                Funct2(props);
            }
            // or return something
        };
    }
    export default Funct1;  
    
    // and here is the test:
    
    describe('Test the Thing', () => {
        it('New Test', () => {
            // Arrange
            const funct2Spy = jasmine.createSpy('Funct2');
            const funct1 = CreateFunct1(funct2Spy);
            const props = "some data";
    
            // Act
            funct1(props);
    
            // Assert
            expect(funct2Spy).toHaveBeenCalledWith(props);
        });
    });
    
    Run Code Online (Sandbox Code Playgroud)
  • 也导出 Function2。这是关于这个主题的主题。由于导出语法的原因,可能需要根据您的场景稍微调整它的示例。