How do I mock a third party package with Jest?

2019-07-29 03:36发布

问题:

I want to be able to test whether or not this Swal() function is called.

It's mocked but I'm not familiar with the Jest mocking library.

This is in my test set up file:

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

So I just want this to return a function.

In my component, Swal is called like this:

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

I think my mock needs to return a named method, so I can spyOn it and check that it was called.

My test:

import Swal from 'sweetalert2';

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

Error:

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

How should I set up my mock and spy as the test fails

回答1:

You can return a mock function jest.fn in your sweetalert.js mock:

module.exports = jest.fn();

And write your test like this:

import { doSomething } from './doSomething';
import Swal from 'sweetalert';

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

Note that I'm using sweetalert in my example code not sweetalert2.

Hope this help!