Am pretty new to JS, but I am trying my best to learn. As it is, I am trying to mock express. Here is my base class (cut down, for testing purposes):
import compression from 'compression';
import express from 'express';
export default class Index{
constructor(){}
spawnServer(){
console.log(express());
let app = express();
app.use(STATIC_PATH, express.static('dist'));
app.use(STATIC_PATH, express.static('public'));
etc...
}
}
And here is the test I am trying to achieve, in a separate test file...:
test('should invoke express once', () =>{
index.spawnServer();
expect(mockExpressFuncs().use.mock.calls.length).toBe(3);
})
My question is - how do I make the test override the require of the class under test - is that even possible? I want to have my Index use a mocked version of express, one that includes express() and express.require.
I did read through the documentation, and attempted something like:
const mockFunction = function() {
return {
use: useFn,
listen: jest.fn()
};
};
beforeEach(() => {
jest.mock('express', () => {
return mockFunction;
})
express = require('express');
});
But that did not work - what am I doing wrong? :(
Thanks.
Create the mock app object and make it be returned by express module.
Then you can check how many times app.use
have been called using either expect(app.use.mock.calls.length).toBe(3)
or better expect(app.use).toHaveBeenCalledTimes(1)
const app = {
use: jest.fn(),
listen: jest.fn()
}
jest.doMock('express', () => {
return () => {
return app
}
})
test('should invoke express once', () => {
expect(app.use).toHaveBeenCalledTimes(1)
})
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