我想测试一个具有返回可观察值的方法的服务,但在 subscribe
内运行 expect
时不断收到此错误
Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)
我尝试增加 Jasmine 的超时间隔,但这不起作用。这是我的代码:
用户.service.ts:
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
subject: Subject<string> = new Subject<string>();
constructor() { }
sendUserNotification(message: string): void {
this.subject.next(message);
}
getUserNotification(): Observable<string> {
return this.subject.asObservable();
}
}
用户.service.spec.ts:
import { TestBed } from '@angular/core/testing';
import { UserService } from './user.service';
describe('UserService', () => {
let service: UserService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(UserService);
});
it('should be able to set and get the registered user', (done) => {
service.sendUserNotification('testNotification');
service.getUserNotification().subscribe((notification: string): void => {
expect(notification).toEqual('testNotification1'); // This is causing the error
done();
});
});
});
请指出可能出现的问题。谢谢!
最佳答案
您的问题是您以错误的顺序进行调用。
因为您是先调度事件,然后订阅,但事实上,您应该先订阅,然后再调度事件。
在简历中,您需要在规范文件中执行以下操作:
import { TestBed } from '@angular/core/testing';
import { UserService } from './user.service';
describe('UserService', () => {
let service: UserService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(UserService);
});
it('should be able to set and get the registered user', (done) => {
service.getUserNotification().subscribe((notification) => {
expect(notification).toEqual('testNotification1');
done();
});
service.sendUserNotification('testNotification');
});
});
关于 Angular Testing - 无法在订阅内运行断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60993368/