Angular TypeError:ApplicationServiceMock.application$.pipe不是函数
我正在尝试对一个Angular 7组件进行单元测试,它在构造函数中有这样一个组件Angular TypeError:ApplicationServiceMock.application$.pipe不是函数,angular,unit-testing,angular-test,Angular,Unit Testing,Angular Test,我正在尝试对一个Angular 7组件进行单元测试,它在构造函数中有这样一个组件 constructor(private store: ApplicationService) { this.store.application$.pipe(first()).subscribe(r => { this.application = r; }); } 现在,当我尝试测试时,我得到了错误 TypeError: ApplicationServiceMock.applicati
constructor(private store: ApplicationService) {
this.store.application$.pipe(first()).subscribe(r => { this.application = r; });
}
现在,当我尝试测试时,我得到了错误
TypeError: ApplicationServiceMock.application$.pipe is not a function
这就是我尝试测试的方式
const ApplicationServiceMock= mock(ApplicationService);
我还尝试使用jasmine.spy,但即使这样也不起作用,并抛出完全相同的错误。我在这里做错了什么或遗漏了什么?我不知道
mock
做了什么。但我假设它只为您的应用程序服务创建一个空包装器。您需要告诉您的spy或mock,它确实有一个名为application$
的属性,该属性返回任何可观察到的内容
所以你需要这样的东西:
const applicationServiceMock = {
application$: () => EMPTY
}
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AppComponent],
providers: [{provide: ApplicationService, useValue: applicationServiceMock}],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
});
it('should be created', () => {
fixture.detectChanges();
expect(component).toBeTruthy();
});
});
const应用程序服务锁={
应用程序$:()=>空
}
描述('AppComponent',()=>{
let组件:AppComponent;
let夹具:组件夹具;
beforeach(异步(()=>{
TestBed.configureTestingModule({
声明:[AppComponent],
提供程序:[{provide:ApplicationService,useValue:applicationServiceMock}],
架构:[无错误\u架构]
})
.compileComponents();
}));
在每个之前(()=>{
fixture=TestBed.createComponent(AppComponent);
组件=fixture.componentInstance;
});
它('应该创建',()=>{
fixture.detectChanges();
expect(component.toBeTruthy();
});
});
由于您要在组件的构造函数中访问可观察对象,因此您需要像我一样使用EMPTY
或使用mock属性中的(此处为您的测试值)
来定义预期可观察对象,因为构造函数在您可以干预它
块之前被调用
如果要使用spyOn
,则需要将订阅代码从组件的构造函数移动到ngOnInit
生命周期挂钩。然后,在调用测试中的第一个fixture.detectChanges()之前,可以更改存根和spyOn
providers: [
{ provide: ApplicationService, useFactory: () => ApplicationServiceMock}
],
const applicationServiceMock = {
application$: () => EMPTY
}
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AppComponent],
providers: [{provide: ApplicationService, useValue: applicationServiceMock}],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
});
it('should be created', () => {
fixture.detectChanges();
expect(component).toBeTruthy();
});
});