简体   繁体   English

如何在observable返回之前调用observable next时测试angular / jasmine中的observable,因为模拟

[英]How to test an observable in angular/jasmine when the observable next is called before the observable is returned, due to mocks

I have the following code 我有以下代码

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

The problem of course is that I need two api calls, so back then I solved it by creating a new subject and returning that. 问题当然是我需要两个api调用,所以当时我通过创建一个新主题并返回它来解决它。

Now I'm writing the functional test.. 现在我正在编写功能测试..

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

The problem is that because of the mocks, the subscribe is called immediately, and therefore the subject.next(user) is called BEFORE the subject is even returned.. 问题是因为模拟,会立即调用subscribe,因此在主题被返回之前调用subject.next(user)

Does anyone know a good way around this? 有没有人知道这方面的好方法?

I found a solution: 我找到了解决方案:

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

By delaying any of the mock observables even for 0 microseconds, the call becomes async and therefore executes after returning the subject. 通过延迟任何模拟可观察量甚至0微秒,调用变为异步,因此在返回主题后执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM