Reputation: 89
I am new in Angular/Jasmine and need help to test a little peace of code.
My ts file createcustomer.ts
My method shoots a boolean event that is listened in another component. I need test if the event below was emitted
export class CreateCustomerComponent {
constructor(public breadCrumbService: BreadCrumbService) { }
emit() {
this.breadCrumbService.createCustomer$.emit(false)
}
}
createcustomer.spec.ts
I wanna test my method above
emit() {
this.breadCrumbService.createCustomer$.emit(false)
}
My test pass and I know how to test a simple emit in component, but an emit of a service I do know yet.
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();
});
I expect createCustomer$ haveBeenCalledWith(false)
Upvotes: 1
Views: 3244
Reputation: 2548
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);
}));
});
Upvotes: 2