我正在为一个简单的node.js模块编写一些测试,该模块返回另一个函数的结果,当前该模块如下所示:
const doAPostRequest = require('./doAPostRequest.js').doAPostRequest
const normalizeResponse = require('./normalizeResponse.js').normalizeResponse
const errorObject = require('./responseObjects.js').errorObject
const successObject = require('./responseObjects.js').successObject
exports.handlePost = (postData) => {
return doAPostRequest(postData).then((res) => {
const normalizedResponse = normalizeResponse(res);
return successObject(normalizedResponse);
}).catch((error) => {
const { statusCode, message } = error;
return errorObject(statusCode, message);
});
}
doAPostRequest
是另一个返回承诺的模块。现在我要测试以下情况:
doAPostRequest
的参数调用一次handlePost
。normalizeResponse
被从doAPostRequest
返回的参数调用。
{li>是一次successObject
被从normalizedResponse
返回的参数调用。
errorObject
返回的参数调用doAPostRequest
(如果有错误)。但是我不知道如何测试函数是否在promise中被调用以及doAPostRequest
是否被首先调用。
目前,我在Chai,Sinn和Sinon-chai图书馆的帮助下为模块编写了以下测试套件。
const sinon = require('sinon');
const chai = require('chai');
const handlePost = require('./handlePost.js').handlePost
const params = { body: 'title': 'foo' }
chai.use(require('sinon-chai'));
it('Calls doAPostRequest', () => {
doAPostRequest = sinon.stub().resolves("Item inserted")
handlePost(params)
expect(doAPostRequest).to.have.been.calledOnce;
expect(doAPostRequest).to.have.been.calledWith(params);
});
it('Calls normalizeResponse', () => {
normalizeResponse = sinon.stub().resolves("result")
return handlePost(params).then((res) => {
expect(normalizeResponse).to.have.been.calledOnce;
expect(normalizeResponse).to.have.been.calledWith("Item inserted");
});
});
但是,测试失败并显示以下错误响应:
AssertionError: expected stub to have been called exactly once, but it was called 0 times
也许我正在忽略某些东西,这不是测试这段代码的正确方法吗?我找到了this主题,问题几乎相同,但是对我来说,显然没有一个函数被调用。这导致我认为我必须忽略某些事情。任何帮助和/或建议将不胜感激。