Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking express with jest?

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.

like image 920
Evangelos Aktoudianakis Avatar asked Jun 18 '17 20:06

Evangelos Aktoudianakis


1 Answers

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)
})
like image 147
Ivan Beldad Avatar answered Sep 16 '22 14:09

Ivan Beldad