【问题标题】:How do I mock a third party package with Jest?如何使用 Jest 模拟第三方包?
【发布时间】:2018-11-17 16:15:03
【问题描述】:

我希望能够测试这个Swal() 函数是否被调用。

它被模拟了,但我不熟悉 Jest 模拟库。

这是在我的测试设置文件中:

jest.mock('sweetalert2', () => {
  return {
    Swal: () => {},
  };
});

所以我只想让它返回一个函数。

在我的组件中,Swal 是这样调用的:

doSomething = () => {
  Swal({
    title: 'Could not log in',
    text: error.message,
    type: 'error',
  });
};

我认为我的 mock 需要返回一个命名方法,所以我可以 spyOn 并检查它是否被调用。

我的测试:

import Swal from 'sweetalert2';

describe('Login Container', () => {
  it('calls Swal', () => {
    doSomething();
    var swalSpy = jest.spyOn(Swal, 'Swal');
    expect(swalSpy).toHaveBeenCalled();
  });
});

错误:

expect(jest.fn()).tohavebeencalled();

当测试失败时我应该如何设置我的模拟和间谍

【问题讨论】:

    标签: javascript reactjs mocking jestjs enzyme


    【解决方案1】:

    您可以在 sweetalert.js 模拟中返回模拟函数 jest.fn

    module.exports = jest.fn();
    

    然后像这样编写你的测试:

    import { doSomething } from './doSomething';
    import Swal from 'sweetalert';
    
    describe('Login Container', () => {
      it('calls Swal', () => {
        expect(Swal).toHaveBeenCalledTimes(0);
        doSomething();
        expect(Swal).toHaveBeenCalledTimes(1);
      });
    });
    

    请注意,我在示例代码中使用的是sweetalert,而不是sweetalert2

    希望对您有所帮助!

    【讨论】:

      【解决方案2】:

      我希望模拟工厂需要返回一个带有default 的对象(因为 import Swal 正在导入默认模块)。像这样的东西(演示 sweetalert v1):

      // extract mocked function
      const mockAlert = jest.fn()
      
      // export mocked function as default module
      jest.mock('sweetalert', () => ({
        default: mockAlert,
      }))
      
      // import the module that you are testing AFTER mocking
      import doSomethingThatAlerts from './doSomethingThatAlerts'
      
      // test suite loosely copied from OP
      describe('Login Container', () => {
        it('calls Swal', () => {
          doSomethingThatAlerts();
      
          // test mocked function here
          expect(mockAlert).toHaveBeenCalled();
        });
      });
      

      【讨论】:

        猜你喜欢
        • 2019-12-14
        • 2018-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-09
        • 2019-06-15
        相关资源
        最近更新 更多