嘲笑第三方图书馆的建设者 [英] Mock 3rd party library constructor with jest

查看:95
本文介绍了嘲笑第三方图书馆的建设者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用玩笑编写单元测试,我必须测试一个从第3方库调用构造函数的函数(测试的目的是检查调用是否具有良好的参数

I'm writing unit tests with jest and I have to test a function that is calling a constructor from a 3rd party library (the goal of the test is to check that the call is made with good arguments

第三个Patry库是Popper.js

The 3rd patry library is Popper.js

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

I have made a jest.spyOn(Popper.prototype, 'constructor').mockImplementation( () => {}) but it is throwing error that came from the inside of the constructor (thus it is not the mock function that has been called)

这是我测试的代码

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

  }); 

推荐答案

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

I finally managed to do something about it. I have created a mock module manually (because jest.genmockfromModule does not seem to work)

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

spy函数是您想知道构造函数是否已通过良好参数调用时可以"spyOn"的函数.

The spy function is the one that you can "spyOn" when you want to know if the constructor has been called with the good parameters

(由于popper.js,这里有3个参数)

(here you have 3 arguments because of popper.js)

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

Thus I use it like so in my spec file :

import Popper from 'popper.js';
 ...
jest.spyOn(Popper.prototype, 'spy');

这篇关于嘲笑第三方图书馆的建设者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆