can anyone help to stub an express handler? My current setup does not seem to work.
controller.ts
import { Request, Response } from 'express';
const test = async (req: Request, res: Response): Promise<Response> => {
try {
console.log('actual test');
return res.status(200).send({ message: 'done' });
} catch (error: unknown) {
return res.status(500).send({ message: 'error' });
}
};
export { test };
route.ts
import { Router } from 'express';
import { test } from './controller';
const testRouter = Router();
export default (router: Router): void => {
router.use('/test', testRouter);
testRouter.get('/test', test);
};
controller.test.ts
import * as sinon from 'sinon';
import { agent as request } from 'supertest';
import { expect } from 'chai';
import * as ctrl from './controller';
import { stubbedApp } from '../test_helpers/globalSetup';
describe('Test Routes', (): void => {
let sandbox: sinon.SinonSandbox;
let stubTest: sinon.SinonStub;
beforeEach((): void => {
sandbox = sinon.createSandbox();
const bar = async () => {
console.log('bar');
return { message: 'done' };
};
stubTest = sandbox.stub(ctrl, 'test').callsFake(bar as any);
});
afterEach((): void => {
sandbox.restore();
});
it('should fetch test', (done): void => {
request(stubbedApp)
.get(`/test`)
.set('Content-Type', 'application/json')
.expect(200)
.then((resp) => {
expect(stubTest.calledOnce).to.be.equal(true);
done();
});
});
});
The test is failing an "actual test" is printing... so that means to me that the stub is not working. Any help or suggestions?
Note stubbedApp is essentially app but it stubs other parts.