samedi 20 juillet 2019

How to test an Express application when using app.use(express.static('public'));

I am unable to mock app.use(express.static('public')); All of my test have worked before i added this line in. I have tested express servers previously using the same approach, however, this is the first time i've used this express.static command.

After adding this line of code in i now get this error in my tests -

TypeError: _express.default.static is not a function

All of my tests pass if i remove the line of

  app.use(express.static('public'));

However, i need this line as i serve up some static images in my app elsewhere.

I have mocked Express as shown in the code below, however, express is a function that returns an Object, this is then used to mock the get(), use() and listen() calls.

Now that i have added express.static('public') it looks like express is also a static object now.

So i need to adjust the

jest.mock('express', () => .... 

section?

Just not sure how to mock this line - app.use(express.static('public'));

Express - Server.js File

const start = () => {
  const port = process.env.port || 7000;
  const app = express();

  app.use(bodyParser.json());
  app.use(cors());
  app.use(express.static('public'));
...
}

Test -  Server.test.js File 


jest.mock('express', () =>
  jest.fn(() => ({
    get: jest.fn(),
    use: jest.fn(),
    listen: jest.fn()
  }))
);

jest.mock('body-parser', () => ({
  json: jest.fn()
}));

jest.mock('cors');

describe('app set up correctly ', () => {
  beforeEach(() => {
    jest.clearAllMocks();
    server.start();
  });

  it('should initialise express server', () => {
    expect(express).toHaveBeenCalled();
  });

I hope to amend the mock call to mock the static call so i no longer get this error TypeError: _express.default.static is not a function and my other tests pass as expected

Any help anyone can give is greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire