angular - 正确测试简单组件的 Observable

标签 angular testing jasmine rxjs

我目前正在测试我创建的一个简单组件,它看起来像这样:

@Input()
public type: string;

private saveSubscription: Subscription;

public ngOnDestroy(): void {
    this.saveSubscription.unsubscribe();
}

public ngOnInit(): void {
    this.onSave();
}

private onSave(): void {
    this.saveSubscription = this.editService.saveSelection.subscribe(() => {
        this.editService.type.next(this.type);
    });
}

在我的测试中,我想确保如果我手动设置输入,然后调用 ngOnInit()editService 发出的值将等于我的值(value)。

it('should set up the subscription for saving', fakeAsync(() => {
    // Arrange
    component.type = 'full';

    // Act
    component.ngOnInit();
    fixture.detectChanges();

    mockedEditService.saveSelection.next();

    // Assert
    mockedEditService.type.subscribe(type => {
        expect(type).toEqual(component.type);
    });
}));

我正在为测试异步代码而苦苦挣扎,并且不确定我是否正确地执行了此操作。即使测试用例不正确,测试也总是通过,我怀疑有问题的代码在做出断言之前没有等待订阅解决。

阅读 Angular test docs ,我已经能够更加熟悉自己了,但我想知道你们是否有任何建议。

谢谢

最佳答案

spec 中,在 mockedEditService.saveSelection.next 之前有 subscription

it('should set up the subscription for saving', fakeAsync(() => {
    // Arrange
    component.type = 'full';

    // START ********* MOVE THIS BLOCK UP
    mockedEditService.type.subscribe(type => {
        expect(type).toEqual(component.type);
    });
    // END ********* MOVE THIS BLOCK UP

    // Act
    component.ngOnInit();
    fixture.detectChanges();

    mockedEditService.saveSelection.next();


}));

关于angular - 正确测试简单组件的 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50137941/

相关文章:

testing - 自动化测试中手写代码和录制脚本的区别

typescript - 了解如何调用 REST Api 并在 Angular 2 中显示来自响应的数据

unit-testing - TDD 中驱动程序和 stub 之间的区别

angular - "required"p-calendar 验证器

selenium - 开发人员在编写代码时应该考虑什么,以便测试人员更容易使用 selenium webdriver 进行自动化测试?

javascript - Jasmine StubRequest 未发送传递的字符串

javascript - Jasmine 自定义匹配器,最重要的是

使用 keycloak "user is not logged in"进行 Angular Testing

angular - 如何从 Angular 2 中的 Assets 文件夹访问文件?

angular - 使用 Protractor 以 Angular 2 进行端到端测试