我正在使用mocha和chai测试node.js控制器文件,无法在我的测试中模拟出响应对象
TestController.ts
export class TestController {
static async getTest(req:any, res:any, next:object) {
console.log("Test");
//some code here
res.status(200).json(result.rows);
}
当我调用API,返回正确的响应等时,这一切都很好。但当我尝试测试这个控制器时,下面是我的测试文件
测试.ts
it('Get Test method', async function () {
let req = {params: {testid: 12345}};
let res:any = {
status: function() { }
};
res.json = '';
let result = await TestController.getTest(req, res, Object);
});
我不知道如何在这里表示响应对象。如果我只是用以下方式声明变量res
let res:any;
我在测试中看到以下错误
TypeError: Cannot read property 'json' of undefined
我不确定我的响应数据结构res应该如何进行此测试。
您应该使用sinon.stub().returnsThis()
来模拟this
上下文,它允许您调用链方法。
例如
controller.ts
:
export class TestController {
static async getTest(req: any, res: any, next: object) {
console.log('Test');
const result = { rows: [] };
res.status(200).json(result.rows);
}
}
controller.test.ts
:
import { TestController } from './controller';
import sinon from 'sinon';
describe('61645232', () => {
it('should pass', async () => {
const req = { params: { testid: 12345 } };
const res = {
status: sinon.stub().returnsThis(),
json: sinon.stub(),
};
const next = sinon.stub();
await TestController.getTest(req, res, next);
sinon.assert.calledWithExactly(res.status, 200);
sinon.assert.calledWithExactly(res.json, []);
});
});
100%覆盖率的单元测试结果:
61645232
Test
✓ should pass
1 passing (14ms)
---------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
controller.ts | 100 | 100 | 100 | 100 |
---------------|---------|----------|---------|---------|-------------------