[英]How to test an observable in angular/jasmine when the observable next is called before the observable is returned, due to mocks
我有以下代碼
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();
})
});
問題是因為模擬,會立即調用subscribe,因此在主題被返回之前調用subject.next(user)
。
有沒有人知道這方面的好方法?
我找到了解決方案:
authApi.authTokenPost.and.returnValue(of(oauthAccessToken).pipe(delay(0)));
通過延遲任何模擬可觀察量甚至0微秒,調用變為異步,因此在返回主題后執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.