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
The 3rd patry library is Popper.js
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)
Here is the code of my test
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();
});
In order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF). Since calls to jest. mock() are hoisted to the top of the file, Jest prevents access to out-of-scope variables.
There are two ways to mock functions: Either by creating a mock function to use in test code, or writing a manual mock to override a module dependency.
The Jest library provides the jest. fn() function for creating a “mock” function. An optional implementation function may be passed to jest. fn() to define the mock function's behavior and return value.
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;
});
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
(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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With