在Jest Node.js测试中从响应中检索JSON
我正在用Jest测试Node/Express应用程序。我从这个Jest测试中得到了200个代码,但是JSON响应没有任何代码在Jest Node.js测试中从响应中检索JSON,node.js,typescript,jestjs,Node.js,Typescript,Jestjs,我正在用Jest测试Node/Express应用程序。我从这个Jest测试中得到了200个代码,但是JSON响应没有任何代码 import * as httpMocks from 'node-mocks-http'; import * as ctrlCars from '../src/controllers/cars'; describe('Test Cars', () => { it('should GET car by ID', () => {
import * as httpMocks from 'node-mocks-http';
import * as ctrlCars from '../src/controllers/cars';
describe('Test Cars', () => {
it('should GET car by ID', () => {
const request = httpMocks.createRequest({
method: 'GET',
url: '/cars',
params: {
id: 2
}
});
const response = httpMocks.createResponse();
const next = function(err) {
console.log('resultNext: ', response._getData());
};
ctrlReels.getCar(request, response, next);
// TODO
console.log('result: ', response.statusCode);
console.log('result: ', response.statusMessage);
console.log('resultData: ', response._getData());
});
});
我在网上找到的示例使用。_getData()获取数据,然后将其解析为JSON,但在我的测试结果中,data不返回任何内容,resultNext根本不输出。在谷歌搜索了很多次之后,我找到了答案,因此我将为下一个找到它的人回答我自己的问题()。在我的案例中实际上有两个问题
ctrlReels.getCar(request, response, next);
response.on('end', () => {
console.log('end');
console.log(response._getData());
done();
});
response.on('send', () => {
console.log('send');
console.log(response._getData());
done();
});
}));
});注意:我不知道代码格式是怎么回事。我试过。。。我真的这么做了。@DavidR你的意思是在测试环境之外?是的,我用的是邮递员,我知道这条路线是有效的