我有一个Node js控制器,它发送一个外部api,我需要使用Sinon来存根它。当我嘲笑这个决心时,它正如预期的那样进行,但当我试图嘲笑拒绝时,我犯了一个我无法理解的错误。
控制器:
let getDocumentByTemplate = (body) => {
return new Promise(async (res, rej)=> {
const accessToken = await getAccessToken()
const fullName = body.firstname + " " + body.lastname
const itemId = body.item_id
const options = {
url: `${process.env.Url}`,
headers: {
'Authorization': `Bearer ${accessToken.token}`,
'Content-Type': 'application/json'
},
data: //some data
}
axios.post(options.url, options.data, {headers:options.headers}).then((data)=>{
return res(data.data)
}).catch( (error)=>{
return rej(error)
})
})
规范文件:
beforeEach(function () {
this.sandbox.axiosStub = this.sandbox.stub(axios, 'post')
})
it('should fail if token invalid', async function () {
token.token= null
const getTokenStub = this.sandbox.stub(cache, 'get')
.callsFake(() => token )
this.sandbox.axiosStub.callsFake(() => Promise.reject(error))
const res = await getDocumentByTemplate(body)
console.log(res)
this.sandbox.assert.calledOnce(getTokenStub)
expect(res.code).to.eql(1537)
expect(res.error).to.eql("invalid_token")
})
作为测试的结果,我得到:
should fail if token invalid: Error: the object { "code": 1537 "error": "invalid_token" } was thrown, throw an Error :)
看起来您正确地模拟了函数,但您也需要在测试中处理promise拒绝。我建议使用chai作为承诺的插件:
const chai = require("chai");
const chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
然后在您的测试使用中,可以预期承诺会被拒绝,如下所示:
await expect(getDocumentByTemplate(body)).to.eventually.be.rejected
.and.to.include({
code: 1537,
error: 'invalid_token'
})