【问题标题】:Angular testing mock subscribed property角度测试模拟订阅属性
【发布时间】:2018-12-13 23:01:28
【问题描述】:

我有一个具有 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);
    });
}

我向另一个 comp 上的用户名发出。但它与这个问题无关。 现在我想模拟 usernameAnnounced 但我遇到了困难。我用spyOn 尝试了它,它给我一个提示:'usernameAnnounced 不是一个函数。 使用spyOnProperties,它会抛出一个:'property is not a getter'。

经过测试的比较

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

    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}`);
});

有人有什么提示吗?

【问题讨论】:

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


    【解决方案1】:

    我总是必须在我的 mock 上构建一个 Subject(或 BehaviorSubject)。

    class authenticationMock{ // is the mock of AuthenticationService
        public usernameAnnounced:Subject<string> = new Subject<string>();
    }
    
    ...
    
    // in Test
    let authenticationService = TestBed.get(AuthenticationService)
    ...
    authenticationService.next('myNewUser');
    

    热烈的问候

    【讨论】:

    • 谢谢伙计,用你的方法我得到了某种“未定义”的结果。但你把我引向了正确的方向。
    【解决方案2】:

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

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

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

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

    【讨论】:

    • 谢谢你,我希望我在 3 小时前找到了这个分析器
    • 实际上是我在过去几个小时内找到的最佳方法!
    猜你喜欢
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 2019-08-06
    • 1970-01-01
    • 2021-10-20
    • 2019-08-22
    • 1970-01-01
    相关资源
    最近更新 更多