使用MockBackend在角单元测试中模拟捕获处理程序

时间:2018-09-10 12:39:21

标签: angular unit-testing

我在服务中有一个如下所示的方法:

public reset(id: string): Promise<boolean> {
    const options = new RequestOptions();
    options.body = { id };

    return this.httpClient.delete(`${this.url}/items`, options)
        .map((response) => (response.json())).toPromise()
        .catch(_ => Promise.reject(false));
}

我正在尝试编写一个单元测试,以确保如果引发异常,则Promise将拒绝false

我一直在使用MockBackend,并提出了类似的内容:

it('should fail to reset', async () => {
    // Arrange
    backend.connections.subscribe((connection: MockConnection) => {
        const options = new ResponseOptions({
            status: 404
        });
        connection.mockError(new Error('Error'));
    });

    // Act
    const result = await service.reset('1234');

    // Assert
    expect(result).toBeUndefined();
}); 

我的catch处理程序未执行,而是看到:

at ZoneQueueRunner.attrs.onException
HeadlessChrome 68.0.3440 (Windows 10.0.0) MyService should fail to reset

at ZoneQueueRunner.attrs.onException (webpack:///./node_modules/zone.js/dist/zone-testing.js?:575:33)
at ZoneDelegate.invoke (webpack:///./node_modules/zone.js/dist/zone.js?:387:26)

0 个答案:

没有答案