[英]Sinon stub is invoking actual async method instead of stubbing
我有一個具有異步功能的中介 times.js 文件,如下所示。 運行 mocha Chai 單元測試時,不會發生對 processTimes() 的存根。 不知道出了什么問題。 我感謝您的幫助。
async function getTimes (request, response) {
let slots;
.....
slots = await processTimes(params, promises);
.....
response.status(200).json(slots);
}
async function processTimes (params, promises) {
return Promise.all(promises).then(function (data) {
return slots;
}
}
並測試規范 times_spec.js 如下。
const chai = require("chai");
const sinon = require("sinon");
const timesMediator = require("times");
describe("times mediator", function () {
var mockResponse = {
set: (key, value) => {
},
status: function (code) {
return {
json: function (json) {
expect(json).not.to.be.empty;
... //some assertions here.
},
};
},
};
beforeEach(function () {
});
afterEach(function (done) {
sinon.restore();
done();
});
it("times", async () => {
sinon.stub(timesMediator, "processTimes").resolves({"a":"A","b":"B"}});
}
timesMediator.getTimes(mockRequest, mockResponse);
}
這是單元測試解決方案:
index.ts
:
exports.getTimes = async function getTimes(request, response) {
let slots;
const params = {};
const promises = [Promise.resolve(1), Promise.resolve(2)];
slots = await exports.processTimes(params, promises);
response.status(200).json(slots);
};
exports.processTimes = async function processTimes(params, promises) {
return Promise.all(promises);
};
index.spec.ts
:
import sinon from 'sinon';
const timesMediator = require('./');
import { expect } from 'chai';
describe('timesMediator', () => {
afterEach(() => {
sinon.restore();
});
it('#getTimes', async () => {
const mProcessTimesResponse = [{ a: 'A', b: 'B' }] as any;
const mReq = {};
const mRes = {
status: sinon.stub().returnsThis(),
json: sinon.stub()
};
const stub = sinon.stub(timesMediator, 'processTimes').resolves(mProcessTimesResponse);
await timesMediator.getTimes(mReq, mRes);
expect(stub.calledWith({}, sinon.match.array)).to.be.true;
expect(mRes.status.calledWith(200)).to.be.true;
expect(mRes.json.calledWith(mProcessTimesResponse)).to.be.true;
});
it('#processTimes', async () => {
const actualValue = await timesMediator.processTimes({}, [Promise.resolve(1)]);
expect(actualValue).to.eql([1]);
});
});
100% 覆蓋率的單元測試結果:
timesMediator
✓ #getTimes
✓ #processTimes
2 passing (13ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.spec.ts | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
源代碼: https : //github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57586444
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.