나는 특급 4를 사용하여 Node.js를 응용 프로그램이이 내 컨트롤러 :약속을 반환하는 다른 함수를 호출하는 함수를 단위 테스트하는 방법?
var service = require('./category.service');
module.exports = {
findAll: (request, response) => {
service.findAll().then((categories) => {
response.status(200).send(categories);
}, (error) => {
response.status(error.statusCode || 500).json(error);
});
}
};
그것은 약속을 반환 내 서비스를 호출합니다. 모든 것은 작동하지만 유닛 테스트를 시도 할 때 문제가 있습니다.
기본적으로, 나는 내 서비스가 반환하는 것을 기반으로 올바른 상태 코드와 본문으로 응답을 플러시합니다.
그래서 모카와 그것을 sinon는 다음과 같은 : 기능 내가 돌아 자체 나는 다음에 내 주장을 연결할 수 있기 때문에 약속을 테스트입니다 때 나는 내 비슷한 시나리오를 테스트 한
it('Should call service to find all the categories', (done) => {
// Arrange
var expectedCategories = ['foo', 'bar'];
var findAllStub = sandbox.stub(service, 'findAll');
findAllStub.resolves(expectedCategories);
var response = {
status:() => { return response; },
send:() => {}
};
sandbox.spy(response, 'status');
sandbox.spy(response, 'send');
// Act
controller.findAll({}, response);
// Assert
expect(findAllStub.called).to.be.ok;
expect(findAllStub.callCount).to.equal(1);
expect(response.status).to.be.calledWith(200); // not working
expect(response.send).to.be.called; // not working
done();
});
.
나는 또한 controller.findAll을 Promise로 랩핑하고 response.send에서 해결하려고 시도했지만 어느 것도 작동하지 않았다.
약속 반환 함수를 호출하는 모든 함수는 비동기이며 약속 자체를 반환해야합니다. 콜백 만받는다면 콜백 기반 API를 테스트해야합니다. – Bergi
Chai를 사용하고 있습니까? 그렇다면 http://chaijs.com/plugins/chai-as-promised/ –
예하지만 테스트중인 기능은 약속의 아들 체인을 약속대로 반환하지 않습니다. 단순한 도움이되지 않습니다. – jbernal