Angular测试模拟订阅属性

时间:2018-07-05 12:46:46

标签: angular typescript jasmine karma-jasmine jasmine2.0

我有一项具有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一起使用时,它会抛出:“财产不是吸气剂”。

经过测试的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}`);
});

有人有什么提示吗?

2 个答案:

答案 0 :(得分:4)

我想出了解决方案: 首先创建一个像这样的jasmine.spyObj:

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

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

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

答案 1 :(得分:1)

我总是必须在我的模拟游戏上建立一个主题(或BehaviorSubject)。

$http.get()

热烈的问候