@cortez.connelly
To create reusable mocks in Mocha, you can use a library like Sinon.js, which provides tools for stubbing and mocking functions. Here's an example of how you can create a reusable mock using Sinon.js in Mocha:
1
|
npm install sinon |
1 2 3 |
function getUser(id) {
// This is a dummy function that fetches a user by their ID
}
|
To create a mock for this function in Mocha, you can do the following:
1 2 3 4 5 6 7 8 9 10 |
const sinon = require('sinon');
// Create a mock for the getUser function
const getUserMock = sinon.stub().returns({ id: 1, name: 'John Doe' });
// Use the mock in your test
it('should return a user', () => {
const user = getUserMock(1);
// Assert that the user returned by the mock is correct
});
|
Now you can reuse getUserMock in multiple tests to mock the getUser function without having to redefine it every time.
1 2 3 |
afterEach(() => {
sinon.restore();
});
|
By following these steps, you can create reusable mocks in Mocha using Sinon.js. This allows you to easily mock functions in your tests without having to redefine them every time.