我正在尝试测试使用 a 的服务BehaviourSubject
,但是我不确定如何。这是我的服务:
export class ProductService {
private changes$: BehaviorSubject<User[]> = new BehaviorSubject([]);
get products() { return this.changes$.asObservable() as Observable<any>; }
getProducts() {
this.http.get(...)
.subscribe((products) => {
this.changes$.next(products);
}
}
filterById(id: number) {
let products = this.products$.getValue().filter(...);
// Maybe I will have some more filter logic here.
// I want to test that the filter logic is returning the correct product
this.changes$.next(products);
}
...
}
这是我的测试。我希望能够测试我的服务的过滤器逻辑。但是由于我在嘲笑数据,所以this.product$.getValue()
将是空的并且过滤器将不会运行。
it('should filter the products and return the correct product)',
inject([ProductService], (service: ProductService) => {
const usersSpy = spyOnProperty(service, 'products', 'get').and.returnValue(Observable.of(mockGetResponse));
service.products.subscribe((res) => {
// How do I continue here?
// the `this.products$.getValue()`
// will not contain any items,
// because I am mocking the data.
service.findByUserId(1);
});
}));