A mocking express with a joke?
I am new to JS but I am trying to learn. Anyway, I'm trying to make fun of the expression. Here is my base class (cut out 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 force the test to override the requirement of the class under test - is this possible? I want my index to use a mocked version of the expression that includes the express () and express.require functions.
I read the documentation and tried something like:
const mockFunction = function() {
return {
use: useFn,
listen: jest.fn()
};
};
beforeEach(() => {
jest.mock('express', () => {
return mockFunction;
})
express = require('express');
});
But it didn't work - what am I doing wrong ?:(
Thank.
source to share
Create a mock app object and return it using express module.
Then you can check how many times app.use
it was called with expect(app.use.mock.calls.length).toBe(3)
or betterexpect(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)
})
source to share