我正在尝试对某个组件的组件进行单元测试,该组件订阅了在服务的构造函数中分配的注入服务的可观察属性。我用spyOnProperty尝试了一下,但是没有用,用该属性伪造了服务,但是没有运气。我在做什么错了?
这是我的SellProductService:
@Injectable({
providedIn: 'root'
})
export class SellProductService{
$soldProducts: Observable<Array<Product>>;
constructor(private store: Store<any>, private http: HttpClient) {
this.$soldProducts= this.store.select('sold');
}
getAll() {
// Some cool httpClient method
}
}
在组件的构造函数中,我正在订阅此变量以获取产品数组。
soldProducts: Array<Product> = [];
constructor(public store: Store<any>,
public sellProductService: SellProductService) {
this.sellProductService.$soldProducts.subscribe((soldProduct: Array<Product>) => {
this.soldProducts = soldProduct;
});
}
我仅出于演示目的更改了一些变量名,请不要注意命名约定。
因此,在我的单元测试中,我尝试使用该变量伪造服务,并使用真实服务并监视返回的值,但我可以使其正常工作。
这是我单元测试的最新版本。
const fakeSoldProducts: Array<Products> = [
{
id: 33,
description: null,
label: "My Cool model name"
},
{
id: 34,
description: null,
label: "My Cool model name 2"
}
}];
describe('ViewProductsComponent', () => {
let component: ViewProductsComponent;
let store: Store<any>;
let fixture: ComponentFixture<ViewProductsComponent>;
let sellProductService: SellProductService;
let http: HttpClient;
const fakeProduct = fakeSoldProducts;
// This is how I was faking the service previously
const fakeSellProductService = {
$soldProducts: new BehaviorSubject<Array<Product>>(fakeSoldProducts)
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ViewProductsComponent],
providers: [
{provide: HttpClient, useValue: {}},
{provide: Store, useClass: TestStore},
SellProductService
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ViewProductsComponent);
component = fixture.componentInstance;
sellProductService = new SellProductService(store, http);
});
it('Should have a list of sold products', async(() => {
let spy = spyOnProperty(sellProductService, "$soldProducts", 'get').and.returnValue(timer(1000).pipe(mapTo(fakeSoldProducts)));
sellProductService.$soldProducts.subscribe((soldProducts: Array<Product>) => {
expect(soldProducts).toEqual(fakeSoldProducts);
});
tick();
discardPeriodicTasks();
}));
});
运行测试时,出现以下错误:
我读到spyOnProperty需要get方法来访问属性值,但是由于在应用程序的很多地方都使用过,所以我无法修改服务。有人可以指导我测试此可观察属性的正确方法吗?