node.js - expect(jest.fn()).toHaveBeenCalled() 失败,即使该函数已被调用

标签 node.js unit-testing jestjs

我正在尝试对返回 promise 的函数进行单元测试。我在验证是否 模拟函数被调用。这是我所做的。,

// codetotest.js
const { SomeModule, isSomething, isSomethingElse } = require("some-module");

exports.somefunction = (param1, param2)=> {
    const someModule = new SomeModule();

    someModule.someMethod("aaa", isSomething);
    someModule.someMethod("bbb", isSomethingElse);

    return (someModule.someOtherMethod(param1)
    .then(()=>{someModule.run(param2)}));
}

这是测试文件,测试说模拟函数没有被调用,但我确实看到模拟函数中的控制台语句正在显示。

// codetotest.test.js
const { somefunction} = require("./codetotest.js");
const { SomeModule } = require("some-module");

jest.mock("some-module", () => {
    return {
        SomeModule: jest.fn().mockImplementation(() => {
            return {
                someMethod: jest.fn((param, fn) => { console.log("This prints!"); }),
                someOtherMethod: jest.fn((param) => { return Promise.resolve(() => { }) }),
                run: jest.fn((param) => { return Promise.resolve(() => { return []; }) })
            }
        })
    };
});

afterEach(() => {
    jest.resetAllMocks();
    jest.restoreAllMocks();
});

describe("Test codetotest.js", () => {
    it("somefunction() - success", async () => {
        const someModule = new SomeModule();

        let output = await somefunction("param1", "param2");

        expect(SomeModule).toHaveBeenCalled();
        expect(someModule.someMethod).toHaveBeenCalled(); // This fails

        await expect(someModule.someOtherMethod.mock.results[0]).resolves;
        expect(someModule.someOtherMethod).toHaveBeenCalled(); // This fails

        await expect(someModule.run.mocks.results[0]).resolves;
        expect(someModule.run).toHaveBeenCalled(); // This fails
    });
});

感谢任何帮助/指点。

谢谢。

P.S:在nodeJs开发和单元测试方面,我还是个初学者。

最佳答案

我在这上面花了很多时间,最后发现实例化的模拟类没有正确返回模拟方法。 This answer 提示我哪里出错了。

因此,我不得不按如下方式更改我的测试文件。

// codetotest.test.js
const { somefunction} = require("./codetotest.js");
const { SomeModule } = require("some-module");

jest.mock("some-module", function() {
    return {
        SomeModule: jest.fn().mockImplementation(function() { // Arrow function cannot be used as constructor
            // Because I was not using the 'this' operator, my constructor always returned empty
            this.someMethod = jest.fn((param, fn) => { console.log("This prints!"); });
            this.someOtherMethod = jest.fn((param) => { return Promise.resolve(() => { }) });
            this.run = jest.fn((param) => { return Promise.resolve(() => { return []; }) });
            return {
                someMethod: this,someMethod,
                someOtherMethod: this.someOtherMethod,
                run: this.run
            }
        })
    };
});

afterEach(() => {
    jest.restoreAllMocks();
});

describe("Test codetotest.js", () => {
    it("somefunction() - success", async () => {
        await somefunction("param1", "param2");

        expect(SomeModule).toHaveBeenCalled();
        expect(SomeModule.mock.instances[0].someMethod).toHaveBeenCalled(); // This works
        expect(SomeModule.mock.instances[0].someOtherMethod).toHaveBeenCalled(); // This works
        expect(someModule.mock.instances[0].run).toHaveBeenCalled(); // This works
    });
});

关于node.js - expect(jest.fn()).toHaveBeenCalled() 失败,即使该函数已被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67538405/

相关文章:

javascript - 语法错误 : Unexpected token angular-cli

node.js - 错误 : Metadata version mismatch for module @ionic-native/core/decorators. d.ts

node.js - Google Speech API 超时时间

ios - XCTest:传递函数参数

java - 调用 getter 和 setter 的映射方法的单元测试

reactjs - 引用错误 : React is not defined in jest tests

debugging - 在 Visual Studio Code 调试器中使用 Jest 时如何配置源映射

node.js - Curl -d 与 --data-binary

java - Jmock/junit 测试

javascript - 如何使用 Jest 和 typescript 模拟模块变量