我正在学习angular以及如何在Angular中编写测试。我遇到错误“无法读取未定义的属性'subscribe'”时,需要一些有关如何模拟BehaviorSubject
的指导。
This is the code for my service:
@Injectable({
providedIn: 'root'
})
export class NumberService {
public number = new BehaviorSubject<string>(undefined);
private lastNumber = undefined;
constructor() { }
next (number: string) {
if (number !== this.number) {
this.number.next(number);
this.lastNumber = number;
}
}
}
然后我在组件中订阅了该号码:
现在是我的测试文件
const restStub = jasmine.createSpyObj('RestService', ['getDetails']);
const NumberStub = jasmine.createSpyObj('NumberService', ['next']);
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ],
imports: [
TranslateModule.forRoot(),
],
providers: [
{ provide: RestService, useValue: restStub },
{ provide: NumberService, useValue: NumberStub},
]
})
.compileComponents();
}));
it('should display ......', () => {
numberStub.next('abc');
restStub.getDeviceInfo.and.returnValue(of(SampleData()));
createComponent();
expect(component.deviceDetails.type).toBe('abc');
});
任何人都可以提供有关如何正确模拟BehaviorSubject
的帮助吗?预先感谢!
答案 0 :(得分:0)
根据您的实现,我创建了一个类似的测试。 对于服务,您只需创建它们的实例并使用它们即可。
pagedList