在Angular 7中,可以使用TestBed
和expectAsync
方法来编写测试用例,并捕获抛出的广播错误。下面是一个示例代码:
import { TestBed, async } from '@angular/core/testing';
import { MyComponent } from './my.component';
describe('MyComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
MyComponent
],
}).compileComponents();
}));
it('should throw broadcast error', async () => {
spyOn(console, 'error'); // 捕获控制台错误输出
const fixture = TestBed.createComponent(MyComponent);
const component = fixture.componentInstance;
// 设置广播错误
const error = new Error('Broadcast error!');
component.broadcastError = error;
// 执行变更检测并等待异步操作完成
fixture.detectChanges();
await fixture.whenStable();
// 断言控制台是否有错误输出
expect(console.error).toHaveBeenCalledWith(error);
});
});
在上面的代码中,首先使用beforeEach
方法设置TestBed
并编译组件。然后,在测试用例中创建组件实例,并设置要抛出的广播错误。接下来,执行变更检测并等待异步操作完成。最后,使用expect
断言console.error
方法是否被调用,并传入了正确的错误对象。
请注意,这里使用了async/await
语法来处理异步操作。此外,为了捕获控制台的错误输出,我们使用了spyOn
来模拟console.error
方法。