在Angular单元测试期间,我们可能需要测试.subscribe()观察者模式的行为。下面是一些示例代码,说明如何在测试中进行。假设我们正在测试一个服务,该服务向远程API发出HTTP请求,并使用Observable返回结果。
首先,需要注入测试的服务,然后创建一个Spy对象来监视.subscribe()方法:
import { TestBed } from '@angular/core/testing';
import { MyService } from './my.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
describe('MyService', () => {
let service: MyService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [MyService]
});
service = TestBed.get(MyService);
httpMock = TestBed.get(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
it('should return an Observable', () => {
const dummyPost = {name: 'Test'};
service.getPost().subscribe(posts => {
expect(posts.length).toBe(1);
expect(posts).toEqual(dummyPost);
});
const req = httpMock.expectOne(`${service.API_URL}/posts`);
expect(req.request.method).toBe('GET');
req.flush(dummyPost);
});
});
在上面的代码中,我们检查了.subscribe()方法返回的Observable对象的结果。通过创建一个虚假的对象(dummyPost),并期望返回的数据与它相同,以测试.subscribe()方法的功能。
最后,需要使用httpMock.verify()方法进行清理。这将确保所有HTTP请求都已完成,并且没有余留数据。