I'm fairly new to testing and even newer to Sinon.
Here I have an express route set up:
import context = require("aws-lambda-mock-context");
this.router.post('/', this.entryPoint);
public entryPoint(req: Request, res: Response, next: NextFunction) {
const ctx = context();
alexaService.execute(req.body, ctx);
ctx.Promise
.then((resp: Response) => res.status(200).json(resp))
.catch((err: Error) => res.status(500));
}
My aim is to test that the post call to /
runs appropriately. My test script is:
describe('/POST /', () => {
it('should post', () => {
chai.request(app)
.post('/v2')
.end((err, res) => {
expect(res).to.be.ok;
});
});
});
Though my test passes it returns status: 500
due to the const ctx = context()
not being recognized. Is there an appropriate/correct way to spy on the variable ctx
and return a mock variable within my test using Sinon? I've been spinning my wheels here for so long.
I'm fairly new to testing and even newer to Sinon.
Here I have an express route set up:
import context = require("aws-lambda-mock-context");
this.router.post('/', this.entryPoint);
public entryPoint(req: Request, res: Response, next: NextFunction) {
const ctx = context();
alexaService.execute(req.body, ctx);
ctx.Promise
.then((resp: Response) => res.status(200).json(resp))
.catch((err: Error) => res.status(500));
}
My aim is to test that the post call to /
runs appropriately. My test script is:
describe('/POST /', () => {
it('should post', () => {
chai.request(app)
.post('/v2')
.end((err, res) => {
expect(res).to.be.ok;
});
});
});
Though my test passes it returns status: 500
due to the const ctx = context()
not being recognized. Is there an appropriate/correct way to spy on the variable ctx
and return a mock variable within my test using Sinon? I've been spinning my wheels here for so long.
1 Answer
Reset to default 4This is a mon problem which I've e accross myself. I've tested multiple solutions, the one I've found to work best is Mockery.
It works like this: before you require your module under test, you tell Mockery to substitute modules the module under test requires with mocks.
For your code, it would look something like this:
const mockery = require('mockery');
const { spy } = require('sinon');
describe('/POST /', () => {
let ctxSpy;
beforeEach(() => {
mockery.enable({
useCleanCache: true,
warnOnUnregistered: false
});
ctxSpy = spy();
mockery.registerMock('"aws-lambda-mock-context"', ctxSpy);
// change this to require the module under test
const myRouterModule = require('my-router-module');
myRouterModule.entryPoint({}, {}, () => {});
return ctxSpy;
});
it('should call ctx', () => {
expect(ctxSpy).called.to.be.ok;
});
afterEach(() => {
mockery.deregisterAll();
mockery.disable();
});
});