Angular测试模拟订阅属性

马可乐

我有2个属性的服务:

服务

...
public usernameAnnounced;
private username: Subject<string> = new Subject<string>();

constructor() {
    super();
    this.usernameAnnounced = this.username.asObservable();
}

在我的组件上,我想订阅该属性:

零件

    public ngOnInit(): void {
    this.service.usernameAnnounced.subscribe((username: string) => {
        this.username = NavbarComponent.capitalizeFirstLetter(username);
    });
}

我发出另一个组合的用户名。但与这个问题无关。现在,我想模拟usernameAnnounced,但遇到困难。我试过了spyOn,结果是:“ usernameAnnounced不是一个函数。” spyOnProperties它抛出我:“属性不是一个getter”。

经过测试的comp。

到目前为止,我的方法如下所示:

    beforeEach(async(() => {
    TestBed.configureTestingModule({
        ...
        declarations: [NavbarComponent],
        providers: [
            ...,
            {provide: service, useValue: authenticationMock}
            ]
        })
        .compileComponents();

    fixture = TestBed.createComponent(NavbarComponent);
}));
...
    it('should render username',() => {
    const underTest = fixture.componentInstance;

    spyOnProperty(authenticationMock, 'usernameAnnounced').and.returnValue({
            subscribe: () => {'boboUser'}}); <== important part here

    underTest.ngOnInit();
    fixture.detectChanges();

    const compiled: HTMLElement = fixture.debugElement.nativeElement.querySelector('#userName');
    const rendered: string = compiled.textContent;

    expect(rendered).toMatch(`Logged in as: ${underTest.username}`);
});

有人有什么提示吗?

马可乐

我用以下方法找出解决方案:首先创建一个jasmine.spyObj,如下所示:

    const authenticationMock: AuthenticationService = jasmine.createSpyObj('AuthenticationService',
    ['usernameAnnounced']);

将其分配给模拟服务:{provide: AuthenticationService, useValue: authenticationMock}而且,单元测试本身只是为您的属性分配了预期的结果:

const spy = TestBed.get(AuthenticationService);
    spy.usernameAnnounced = Observable.of('dummyUser');

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章