用玩笑模拟第 3 方库构造函数

Cha*_*eBE 5 javascript unit-testing typescript jestjs popper.js

我正在用 jest 编写单元测试,我必须测试一个从 3rd 方库调用构造函数的函数(测试的目标是检查调用是否使用了正确的参数

第三个 patry 库是 Popper.js

我做了一个jest.spyOn(Popper.prototype, 'constructor').mockImplementation( () => {})但它抛出来自构造函数内部的错误(因此它不是被调用的模拟函数)

这是我的测试代码

  import Popper from 'popper.js';

  it('should call Popper constructor with correct argument', () => {
    // Arrange
    jest.mockImplementation(Popper.prototype, 'constructor', () => {});
    const refElem = document.createElement('div');
    const popElem = document.createElement('div');
    const placement = 'top';
    const container = document.createElement('div');

    // Act
    popup.create(refElem, popElem, placement, container);

    // Assert
    expect(Popper.prototype.constructor).toHaveBeenCalled();

  }); 
Run Code Online (Sandbox Code Playgroud)

Cha*_*eBE 5

我终于设法做些什么了。我手动创建了一个模拟模块(因为jest.genmockfromModule似乎不起作用)

jest.mock ('popper.js', () =>
{
  class Popper {
    constructor(a,b,c){
      this.spy(a,b,c);
    }
    spy(a,b,c) {}
    destroy() {}
  }
  return Popper;
});
Run Code Online (Sandbox Code Playgroud)

spy 函数是当您想知道构造函数是否已使用正确参数调用时可以“窥探”的函数

(这里有 3 个参数,因为popper.js

因此我在我的规范文件中像这样使用它:

import Popper from 'popper.js';
 ...
jest.spyOn(Popper.prototype, 'spy');
Run Code Online (Sandbox Code Playgroud)