要测试的代码:
async showSuccess() {
this.msgs.push({severity: 'success', summary: 'Success.'});
await delay(1000);
this.msgs = [];
}
这是我尝试过的测试,但没有涵盖delay(1000),因此也没有this.msgs = []
it('should show message', async() => {
spyOn(component, 'showSuccess');
component.showSuccess();
expect(component.showSuccess).toHaveBeenCalled();
});
覆盖了方法签名行,覆盖了要推送的消息,但没有覆盖最后两行。
答案 0 :(得分:1)
因此,这是一个完整的基于Mocha / Chai的示例,该示例可以正常工作,并且应展示如何像您尝试的那样实施测试:
const chai = require('chai');
const spies = require('chai-spies');
chai.use(spies);
const expect = chai.expect;
class ClassThatDoesStuff {
randomArray = [];
async doStuff() {
console.log('Do stuff...');
await new Promise((resolve) => setTimeout(resolve, 1000));
this.randomArray.push('random entry');
console.log('Done doing stuff');
}
}
describe('Async Function Testing', () => {
let objectThatDoesStuff = new ClassThatDoesStuff();
it('should do things', async () => {
const spy = chai.spy.on(objectThatDoesStuff, 'doStuff');
await objectThatDoesStuff.doStuff();
expect(spy).to.have.been.called();
expect(objectThatDoesStuff.randomArray).to.contain('random entry');
});
});
最重要的一点是:在断言异步函数已完成某件事之前,请确保等待该函数完成(本例中使用await objectThatDoesStuff.doStuff()
,在本例中使用await component.showSuccess()
)。