【问题标题】:Stub chained promises with sinon带有 sinon 的 Stub 链式承诺
【发布时间】:2021-02-23 23:33:37
【问题描述】:
let image = await object
.firstCall(params)
.promise()
.then(data => {
return data
})
.catch(err => {
console.(err)
});
用 sinon 存根链式承诺的方法是什么?我尝试了以下方法,但没有运气
promiseStub = sinon.stub().callsArg(0).resolves("something");
firtCallStub = sinon.stub(object, "firstCall").returns(this.promiseStub);
【问题讨论】:
标签:
javascript
express
promise
sinon
stub
【解决方案1】:
单元测试解决方案:
index.ts:
import { object } from './obj';
export async function main() {
const params = {};
return object
.firstCall(params)
.promise()
.then((data) => {
return data;
})
.catch((err) => {
console.log(err);
});
}
obj.ts:
export const object = {
firstCall(params) {
return this;
},
async promise() {
return 'real data';
},
};
index.test.ts:
import { main } from './';
import { object } from './obj';
import sinon from 'sinon';
import { expect } from 'chai';
describe('64795845', () => {
afterEach(() => {
sinon.restore();
});
it('should return data', async () => {
const promiseStub = sinon.stub(object, 'promise').resolves('fake data');
const firtCallStub = sinon.stub(object, 'firstCall').returnsThis();
const actual = await main();
expect(actual).to.be.equal('fake data');
sinon.assert.calledWithExactly(firtCallStub, {});
sinon.assert.calledOnce(promiseStub);
});
});
单元测试结果:
64795845
✓ should return data
1 passing (32ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 66.67 | 100 | 40 | 66.67 |
index.ts | 83.33 | 100 | 66.67 | 83.33 | 12
obj.ts | 33.33 | 100 | 0 | 33.33 | 3-6
----------|---------|----------|---------|---------|-------------------