代码之家  ›  专栏  ›  技术社区  ›  MarcoLe

角度测试模拟订阅属性

  •  1
  • MarcoLe  · 技术社区  · 8 年前

    我有一个具有两个属性的服务:

    服务

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

    我发送到另一个比赛的用户名。但这与这个问题无关。 现在我想模仿宣布的用户名,但我有困难。我试过了 spyOn 它给了我一个提示:“已宣布的用户名不是一个函数。” 具有 spyOnProperties 它给了我一个“属性不是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}`);
    });
    

    有人有什么提示吗?

    2 回复  |  直到 8 年前
        1
  •  4
  •   MarcoLe    8 年前

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

    {provide: AuthenticationService, useValue: authenticationMock}

    const spy = TestBed.get(AuthenticationService);
        spy.usernameAnnounced = Observable.of('dummyUser');
    
        2
  •  1
  •   JanRecker    8 年前

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

    推荐文章