我是Angular / Jasmine的新手,需要帮助来测试一点和平的代码。
我的ts文件createcustomer.ts
我的方法拍摄一个布尔事件,该事件在另一个组件中侦听。我需要测试是否发出了以下事件
export class CreateCustomerComponent {
constructor(public breadCrumbService: BreadCrumbService) { }
emit() {
this.breadCrumbService.createCustomer$.emit(false)
}
}
createcustomer.spec.ts
我想在上面测试我的方法
emit() {
this.breadCrumbService.createCustomer$.emit(false)
}
我的测试合格,并且我知道如何测试组件中的简单发射,但是我尚不知道服务的发射。
describe('CreateCustomerComponent ', () => {
let component: CreateCustomerComponent ;
let fixture: ComponentFixture<CreateCustomerComponent >;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ ],
declarations: [
createCustomerComponent
],
schemas: [
NO_ERRORS_SCHEMA
],
providers: [
{ provide: BreadCrumbService }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CreateBotComponent);
component = fixture.componentInstance;
});
it('should create the component CreateCustomerComponent ', () => {
expect(component).toBeTruthy();
});
我希望createCustomer $ haveBeenCalledWith(false)
答案 0 :(得分:0)
describe('CreateCustomerComponent ', () => {
let component: CreateCustomerComponent ;
let fixture: ComponentFixture<CreateCustomerComponent >;
beforeEach(async(() => {
TestBed.configureTestingModule({
...
providers: [
{
provide: BreadCrumbService,
// use can describe structure of mocked object with useValue or use declare mock class and bind it with useClass
useValue: { createCustomer$: { emit: jasmine.createSpy('emit') } }
}
]
})
.compileComponents();
}));
...
// what method do we test
describe('.emit()', () => {
// expected behaviors
it('should emit false via createCustomer$ from breadCrumbService', inject([BreadCrumbService], (service: BreadCrumbService) => {
component.emit();// or you can play around and try to trigger it via template interactions
expect(service.createCustomer$.emit).toHaveBeenCalledWith(false);
}));
});