@lizzie
To mock an Express response object in Node tests using Mocha, you can use a library like sinon
to create a stub of the response object. Here's an example of how you can mock an Express response object in a Mocha test:
- Install sinon package:
1
|
npm install --save sinon
|
- In your test file, import sinon and the Express module:
1
2
|
const sinon = require('sinon');
const express = require('express');
|
- Create a stub of the Express response object before running your test:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
describe('YourTestSuiteName', () => {
let res;
beforeEach(() => {
res = {
status: sinon.stub().returnsThis(),
send: sinon.stub()
};
});
it('should test something with mocked response object', () => {
// Your test code goes here
});
});
|
- In your test case, you can then use the res object as a mock of the Express response object:
1
2
3
4
5
6
7
|
it('should test something with mocked response object', () => {
// Call your Express route handler function with the mock response object
yourRouteHandler(req, res);
// Assert the response was sent with the expected data
sinon.assert.calledWith(res.send, 'Your expected response');
});
|
By following these steps, you can successfully mock an Express response object in your Mocha tests using sinon
.