我对测试相当陌生,对 Sinon 更陌生。
这里我设置了一条快速路线:
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));
}
我的目标是测试对 /
的 post 调用是否正常运行。我的测试脚本是:
describe('/POST /', () => {
it('should post', () => {
chai.request(app)
.post('/v2')
.end((err, res) => {
expect(res).to.be.ok;
});
});
});
尽管我的测试通过了,但由于 const ctx = context()
未被识别,它返回 status: 500
。是否有适当/正确的方法来监视变量 ctx
并使用 Sinon 在我的测试中返回模拟变量?我已经在这里旋转了很长时间。
最佳答案
这是我自己遇到的一个常见问题。我测试了多种解决方案,我发现效果最好的是 Mockery .
它是这样工作的:在你 require 被测模块之前,你告诉 Mockery 用 mocks 替换被测模块需要的模块。
对于您的代码,它看起来像这样:
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();
});
});
关于javascript - 使用 Sinon 模拟常量/变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42603341/