Iqe*_*qen 5 javascript unit-testing mocha.js sinon chai
我对测试还很陌生,甚至对 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));
}
Run Code Online (Sandbox Code Playgroud)
我的目标是测试 post 调用是否/正确运行。我的测试脚本是:
describe('/POST /', () => {
it('should post', () => {
chai.request(app)
.post('/v2')
.end((err, res) => {
expect(res).to.be.ok;
});
});
});
Run Code Online (Sandbox Code Playgroud)
虽然我的测试通过了它status: 500由于const ctx = context()未被识别而返回。是否有适当/正确的方法来监视变量ctx并使用 Sinon 在我的测试中返回模拟变量?我在这里转了这么久。
这是一个常见问题,我自己也遇到过。我测试了多种解决方案,我发现效果最好的一个是Mockery。
它的工作原理如下:在您需要测试中的模块之前,您告诉 Mockery 用模拟替换测试中的模块所需的模块。
对于您的代码,它看起来像这样:
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();
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5833 次 |
| 最近记录: |