angular - 如何以 Angular Testing 以下异步函数?

标签 angular typescript testing

要测试的代码:

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/

相关文章:

node.js - 将 ChaiHttp 与 beforeEach 或 before 方法一起使用

typescript - 如何避免类中的代码重复?

typescript - 如何使用类验证器验证嵌套 js 中的 uuid 数组?

c# - 使用 Moq 对继承层次结构进行单元测试

c++ - 如何为依赖操作系统的类编写测试

angular - Ionic 2 - 服务意外 token 错误

javascript - 表单验证不适用于 Angular ?

通过 *ngFor 在数组中以 Angular 显示对象

Angular Material matInput 内容右对齐

c# - Selenium WebDriver 偶尔抛出超时异常