我正在开发一个基于Angular的应用程序,我需要进行组件通信。我正在利用服务来实现理想的工作。
我很难测试观察者。以下是所有课程的代码段:
TestComponent.ts文件
export class TestComponent implements OnInit {
id: number = -1;
message: string;
constructor(private testService: TestService) { }
ngOnInit() {
this.testService.test1$
.subscribe((id: number) => {
this.id = id;
});
this.message= this.testService.getMessage();
}
}
TestService.ts
export class TestService {
onTestChange1 = new Subject<number>();
onTestChange2 = new Subject<string>();
// Observable string streams
test1$ = this.onTestChange1.asObservable();
test2$ = this.onTestChange2.asObservable();
getTest1() {
this.onTestChange1.next(1);
}
getTest2() {
this.onTestChange2.next('Hi from 2');
}
getMessage(): string {
return 'Hi';
}
}
TestComponent规范文件:
fdescribe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let test: TestMockService;
beforeEach(async(() => {
test = new TestMockService();
TestBed.configureTestingModule({
declarations: [ TestComponent ],
providers: [
{provide: TestService, useValue: test}
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
it('should message to be true Hi', async(() => {
const dataStub = fixture.debugElement.injector.get(TestService);
const spy = spyOn(dataStub, 'getMessage').and.returnValue('Hi');
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(component.message1).toBe('Hi');
});
}));
it('id should be equal to 1', async(() => {
const dataStub = fixture.debugElement.injector.get(TestService);
const spy = spyOn(dataStub, 'getTest1').and.returnValue(Observable.of(1));
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(component.id).toBe(1);
});
}));
});
“id”正在测试的最后一个测试失败了,我不确定为什么!
我知道我错过了一些非常小而重要的东西,这就是为什么我的代码无效。如果有人能帮助我理解和纠正我的代码,真的很棒。
快速回复将不胜感激! 谢谢!