我正在尝试测试一个behaviorSubject,但是不断得到:
Error: <spyOnProperty> : Property myBehaviorSubject$ does not have access type get
这是我在myService中声明我的behaviorSubject的方式:
myBehaviorSubject$ = new BehaviorSubject<Array<ObjectA>>([{name: 'name1'}]);
和我的测试:
describe(`myMethod`, () => {
beforeEach(() => {
myServiceMock = {
myBehaviorSubject$: new BehaviorSubject<Array<ObjectA>>(null)
};
spyOnProperty(myServiceMock, 'myBehaviorSubject$', 'get').and.returnValue(observableOf([{name: 'name1'}] as Array<ObjectA>));
});
it('should access behaviorSubject', () => {
myServiceMock.myBehaviorSubject$.subscribe( result => {
//expect;
});
});
});
答案 0 :(得分:1)
您正在嘲笑属性访问的返回值,这意味着您实际上根本没有直接使用该属性。建议不要直接创建间谍,就像这样:
beforeEach(() => {
myServiceMock = {
myBehaviorSubject$: jasmine.createSpy('myBehaviorSubject$')
.and.returnValue(observableOf([{name: 'name1'}] as Array<ObjectA>))
};
});
这具有与上面完全相同的效果,但是它不会创建BehaviorSubject
的新实例,而该实例似乎并未使用。