示例:
class MyClass {
public log(): void {
console.log(this);
}
}
单元测试.js
const instance = new MyClass();
expect(instance.log).toHaveBeenCalled();
避免引用未绑定方法错误,而尝试进行单元测试时已抛出错误。使用箭头功能而不是在 linting 中添加"白名单"选项更好吗?任何帮助将不胜感激
TypeScript 会标记这一点,因为您的原始函数引用this
。请注意,TypeScript 不知道开玩笑,以及(大概(你用来跟踪呼叫的模拟或间谍。
我解决这个问题的方法是命名模拟并直接引用它,以便 TypeScript 和 jest 可以就模拟的类型达成一致。
在您的示例中,我们正在监视现有方法,我们将间谍命名为:
const instance = new MyClass();
const logSpy = jest.spyOn(object, methodName);
expect(logSpy).toHaveBeenCalled();
在构建复杂模拟的情况下,我们从其他命名模拟中构建模拟:
const sendMock = jest.fn()
jest.mock('electron', () => ({
ipcRenderer: {
send: sendMock,
},
}));
// ...
expect(sendMock).toHaveBeenCalledTimes(1);
我也遇到了这个问题(开玩笑与打字稿-eslint(。 这是所讨论的 eslint 规则。
我尝试了许多解决方案(围绕绑定模拟函数(,虽然我仍然愿意找到一种优雅的方式来静音 linting 规则,而不会使我的测试显着降低可读性,但我决定为我的测试禁用该规则。
就我而言,我正在模拟电子ipcRenderer函数:
import { ipcRenderer } from 'electron';
jest.mock('electron', () => ({
ipcRenderer: {
once: jest.fn(),
send: jest.fn(),
removeAllListeners: jest.fn(),
},
}));
然后在测试中,期望调用发送模拟:
expect(ipcRenderer.send).toHaveBeenCalledTimes(1);
直接绑定函数,例如
expect(ipcRenderer.send.bind(ipcRenderer)).toHaveBeenCalledTimes(1);
。通过了 Eslint 规则,但 Jest 不喜欢它:
expect(received).toHaveBeenCalledTimes(expected)
Matcher error: received value must be a mock or spy function
Received has type: function
Received has value: [Function bound mockConstructor]
您必须禁用@typescript-eslint/unbound-method
并启用jest/unbound-method
规则。后者扩展了第一个,所以你仍然需要依赖@typescript/eslint
。
'@typescript-eslint/unbound-method': 'off',
'jest/unbound-method': 'error',