要测试的代码:
async showSuccess() {
this.msgs.push({severity: 'success', summary: 'Success.'});
await delay(1000);
this.msgs = [];
}
这是我尝试过的测试,但未涵盖 await delay(1000),因此也未涵盖 this.msgs = []
it('should show message', async() => {
spyOn(component, 'showSuccess');
component.showSuccess();
expect(component.showSuccess).toHaveBeenCalled();
});
覆盖了方法签名行和正在推送的消息,但没有覆盖最后两行。
最佳答案
所以这是一个完整的基于 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()
)。
关于angular - 如何以 Angular Testing 以下异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57311879/