如何用 Jest 覆盖(或模拟)类方法以测试函数?



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

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

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;
}
}

有一个规范文件:

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...嘲笑失败了。

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

你可以帮我吗?谢谢你的时间。

嗯。我找到了解决方案。

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

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();
}
}

最新更新