【问题标题】:How to overwrite (or mock) a class method with Jest in order to test a function?如何用 Jest 覆盖(或模拟)类方法以测试函数?
【发布时间】:2018-11-15 21:42:50
【问题描述】:

我对调用类的函数的单元测试有疑问。似乎总是调用“官方”类实例而不是我的模拟类。我无法强制我的函数使用我的模拟实例......

有一个文件包含我要测试的功能:

const myClass = require('./myClass');
const instance = new myClass();

module.exports.functionToTest = async function () {

    // Some stuff...

    const value = await instance.myMethod();

    // Some stuff that define a result variable (partially with value).

    return result;
}

有一个包含我的类定义的文件:

module.exports = class myClass {
    async myMethod() {
        const result = await someStuffWillResolveMaybeTrueOrFalse();

        console.log('We used the original myMethod... Mocking has failed.');

        return result;
    }
}

有一个spec文件:

const myFile = require('./myFile');
const myClass = require('./myClass');

describe('My test', async () => {
    it('should mock myClass.myMethod in order to return false', () => {
        const instance = new myClass();
        instance.myMethod = jest.fn().mockResolvedValue(false);

        const result = await myFile.functionToTest();

        expect(result).toBeTruthy();
    }
}

不幸的是,我的测试通过了(因为 myMethod 返回“true”)并记录“我们使用了原始的 myMethod...Mocking 失败。”

所以我想通过模拟 myMethod 返回 false 来让我的测试总是失败。

你能帮帮我吗?感谢您的宝贵时间。

【问题讨论】:

标签: javascript node.js unit-testing jestjs


【解决方案1】:

嗯。我找到了解决办法。

看。使用目标函数更改我的文件。

const myClass = require('./myClass');
// const instance = new myClass(); <== Not here...

module.exports.functionToTest = async function () {
    const instance = new myClass(); // <== ...but there.

    // Some stuff...

    const value = await instance.myMethod();

    // Some stuff that define a result variable (partially with value).

    return result;
} 

还有我的规范文件:

const myFile = require('./myFile');

// I specify to Jest that I'll mock a file
jest.mock('./myClass');
const myClass = require('./myClass');

// I prepare the mock function. In that case a promise wich resolve 'false'
const mMock = jest.fn().mockResolvedValue(false);

// I mock the method 'myMethod' in 'myClass'
myClass.mockImplementation(() => {
    return {
        myMethod: mMock
    };
});


// Then, I just take the test
describe('My test', async () => {
    it('should mock myClass.myMethod in order to return false', () => {
        const result = await myFile.functionToTest();

        expect(result).toBeFalsy();
    }
}

【讨论】:

    猜你喜欢
    • 2020-03-12
    • 2020-11-05
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 2021-11-01
    相关资源
    最近更新 更多