我正在使用sinon对具有回调函数的对象实例进行存根,我该如何测试呢? 我不知道该如何测试,这使我出错。
这是将js与sinon和mocha一起使用。
函数是:
import tracker from 'pivotaltracker';
export async function getPivotalProjects(token) {
const clientTracker = new tracker.Client(token);
const userProjects = () => new Promise((resolve, reject) => {
clientTracker.projects.all((error, projects) => (projects ? resolve(projects) : reject(error)));
});
return userProjects();
测试是:
import tracker from 'pivotaltracker';
let spyTracker;
beforeEach(() => {
spyTracker = sinon.stub(tracker, 'Client');
});
it('should do the request to get the activities from projects.', async () => {
spyTracker.callsArgWith(1, null, [true, 'token']);
// spyTracker.projects.all.returns('token');
await PivotalTrackerApi.getPivotalProjects('token');
sinon.assert.threw(spyTracker);
spyTracker.restore();
});
这有什么问题?如果有人能帮助我,那就太好了。
答案 0 :(得分:0)
getPivotalProjects
可以简化为:
export async function getPivotalProjects(token) {
const clientTracker = new tracker.Client(token);
await new Promise((resolve, reject) => {
clientTracker.projects.all((error, projects) => (projects ? resolve(projects) : reject(error)));
});
}
...它可以像这样进行测试:
let clientStub;
beforeEach(() => {
clientStub = sinon.stub(tracker, 'Client');
});
it('should do the request to get the activities from projects.', async () => {
const allSpy = sinon.spy();
clientStub.callsFake((token) => ({ projects: { all: allSpy } }));
const promise = PivotalTrackerApi.getPivotalProjects('token');
sinon.assert.calledWith(clientStub, 'token'); // Success!
sinon.assert.called(allSpy); // Success!
const callback = allSpy.lastCall.args[0];
callback(null, 'my projects');
const result = await promise;
expect(result).to.equal('my projects'); // Success!
});