可以将“no-unbound-method”列入单元测试白名单吗?我将来是否有可能因白名单而遇到问题

Sou*_*ivi 5 angularjs typescript tslint

例子:

class MyClass {
  public log(): void {
    console.log(this);
  }
}
Run Code Online (Sandbox Code Playgroud)

单元测试.js

const instance = new MyClass();
expect(instance.log).toHaveBeenCalled(); 
Run Code Online (Sandbox Code Playgroud)

尝试进行单元测试时避免引用未绑定方法错误。使用箭头函数比在 linting 中添加“白名单”选项更好吗?任何帮助将不胜感激

Sha*_*mes 11

TypeScript 会标记这一点,因为您的原始函数引用了this. 请注意,TypeScript 不知道笑话以及(大概)您用来跟踪调用的模拟或间谍。

我解决这个问题的方法是命名模拟并直接引用它,以便 TypeScript 和 jest 可以就模拟的类型达成一致。

在您的示例中,我们正在监视现有方法,我们将间谍命名为:

const instance = new MyClass();
const logSpy = jest.spyOn(object, methodName);
expect(logSpy).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)

在构建复杂的模拟的情况下,我们会从其他命名的模拟中构建模拟:

const sendMock = jest.fn()
jest.mock('electron', () => ({
  ipcRenderer: {
    send: sendMock,
  },
}));
// ...
expect(sendMock).toHaveBeenCalledTimes(1);
Run Code Online (Sandbox Code Playgroud)


小智 0

我也遇到这个问题(jest vs. typescript-eslint)。 就是所讨论的 eslint 规则。

我尝试了多种解决方案(围绕绑定模拟函数),虽然我仍然愿意寻找一种优雅的方法来沉默 linting 规则,而又不会使我的测试的可读性明显降低,但我决定禁用我的测试的规则。

就我而言,我正在嘲笑电子 ipcRenderer 函数:

import { ipcRenderer } from 'electron';

jest.mock('electron', () => ({
  ipcRenderer: {
    once: jest.fn(),
    send: jest.fn(),
    removeAllListeners: jest.fn(),
  },
}));
Run Code Online (Sandbox Code Playgroud)

然后在测试中,期望调用发送模拟:

expect(ipcRenderer.send).toHaveBeenCalledTimes(1);
Run Code Online (Sandbox Code Playgroud)

直接绑定函数,例如

expect(ipcRenderer.send.bind(ipcRenderer)).toHaveBeenCalledTimes(1);
Run Code Online (Sandbox Code Playgroud)

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