【问题标题】:How to test an observable in angular/jasmine when the observable next is called before the observable is returned, due to mocks由于模拟,在返回可观察对象之前调用可观察对象时如何在角度/茉莉花中测试可观察对象
【发布时间】:2019-05-03 12:00:25
【问题描述】:

我有以下代码

login(user: string, pass: string): Observable<User> {
    const subject = new Subject<User>();

    this.authApi.authTokenPost(user, pass)
        .subscribe((token: OAuthAccessToken) => {
            this.tokenService.save(token);
            this.userApi.fetch()
                .subscribe((user: User) => {
                    subject.next(user);
                });
        }) // removed error handling for brevity

    return subject;
}

问题当然是我需要两个 api 调用,所以当时我通过创建一个新主题并返回它来解决它。

现在我正在编写功能测试..

const user: User = {id: '1234'};

const authApi = jasmine.createSpyObj('AuthApi', ['authTokenPost']);
const tokenService = jasmine.createSpyObj('TokenService', ['save']);
const userApi = jasmine.createSpyObj('UserService', ['fetch']);

beforeEach(() => {    
    authApi.authTokenPost.and.returnValue(of(oauthAccessToken));
    userService.fetch.and.returnValue(of(user));

    authenticationService = new AuthService(authApi, tokenService, userApi);
});

it('should login', (done) => {
    authService.login('user', 'pass')
        .subscribe((user2) => {
            expect(user2).toEqual(user);
            done();
        })
});    

问题是由于模拟,订阅被立即调用,因此subject.next(user) 在主题被返回之前被调用..

有人知道解决这个问题的好方法吗?

【问题讨论】:

    标签: angular unit-testing jasmine automated-tests


    【解决方案1】:

    我找到了解决办法:

    authApi.authTokenPost.and.returnValue(of(oauthAccessToken).pipe(delay(0)));
    

    通过将任何模拟 observables 延迟甚至 0 微秒,调用变为异步,因此在返回主题后执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-16
      • 2018-04-11
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      • 2019-09-09
      相关资源
      最近更新 更多