【问题标题】:can 'no-unbound-method' be whitelisted for unittests? Is there any possibility of me facing an issue in future because of whitelisting单元测试可以将“no-unbound-method”列入白名单吗?由于白名单,我将来是否有可能面临问题
【发布时间】:2020-03-26 18:45:18
【问题描述】:

例子:

class MyClass {
  public log(): void {
    console.log(this);
  }
}

unittests.js

const instance = new MyClass();
expect(instance.log).toHaveBeenCalled(); 

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

【问题讨论】:

    标签: angularjs typescript tslint


    【解决方案1】:

    TypeScript 会标记这一点,因为您的原始函数引用了 this。请注意,TypeScript 不知道 jest 以及(可能)您用来跟踪调用的 mock 或 spy。

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

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

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

    【讨论】:

      【解决方案2】:

      我也遇到了这个问题(jest vs. typescript-eslint)。 This 是有问题的 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]
      

      【讨论】:

        【解决方案3】:

        您必须禁用@typescript-eslint/unbound-method 并启用jest/unbound-method 规则。后者扩展了第一个,所以你仍然需要依赖@typescript/eslint

        '@typescript-eslint/unbound-method': 'off',
        'jest/unbound-method': 'error',
        

        【讨论】:

          猜你喜欢
          • 2012-08-14
          • 1970-01-01
          • 1970-01-01
          • 2017-09-18
          • 1970-01-01
          • 2016-03-13
          • 1970-01-01
          • 2021-12-08
          • 2016-01-19
          相关资源
          最近更新 更多