bikk-uk / jest-mock-express

A lightweight Jest mock for unit testing Express
MIT License
50 stars 7 forks source link

Provide a way to store the data in the response object #66

Closed paztis closed 3 months ago

paztis commented 2 years ago

currently the only way to test the data is to call

expect(res.send).toHaveBeenCalledWith(...)
expect(res.json).toHaveBeenCalledWith(...)
expect(res.end).toHaveBeenCalledWith(...)

I may be important to store the data in you mock to let it be accessed with expect(res.data).toBe(...)

It may be done in your mock by saving the args of the send / josn / end

rdimascio commented 2 years ago

You can access the data returned with res.json.mock.calls[0][0]

Joshandrews43 commented 1 year ago

You can access the data returned with res.json.mock.calls[0][0]

This does not work:

import handler from './handler';

describe('Basic express test example', () => {
  it('returns pong', async () => {
    const req = getMockReq();
    const { res } = getMockRes();
    await handler.ping(req, res); // (_, res) => res.send('pong');
    const response = res.json.mock.calls[0][0] // is empty array
    expect(response).toBe("pong");
  });
});
aboyce commented 3 months ago

Closing this now as it's gone stale and an answer has been provided.