let image = await object
.firstCall(params)
.promise()
.then(data => {
return data
})
.catch(err => {
console.(err)
});
What's the way to stub the chained promises with sinon
? I've tried the following, but with no luck
promiseStub = sinon.stub().callsArg(0).resolves("something");
firtCallStub = sinon.stub(object, "firstCall").returns(this.promiseStub);
Unit test solution:
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);
});
});
unit test result:
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
----------|---------|----------|---------|---------|-------------------
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.