'How to test a method that have service and subscribe error in Angular with Test?
If I have the following createHero method in a component:
@Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
constructor(
private heroService: HeroService,
private globalService: GlobalService
) {}
ngOnInit(): void {}
createHero(hero: Hero): void {
this.heroService.addHero(hero).subscribe(
(response) => {
this.globalService.showToast();
this.goBack();
},
(error) => {
this.handleErrors(error);
}
);
}
}
How can I test in Angular with Jest? How to test the response and error branch?
My test file look like as follow:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HeroesComponent } from './sample.component';
import { of } from 'rxjs';
describe('HeroesComponent', () => {
let component: HeroesComponent;
let fixture: ComponentFixture<HeroesComponent>;
let heroServiceMock: any;
let globalServiceMock: any;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ HeroesComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(HeroesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
beforeEach(() => {
heroServiceMock = {
addHero: jest.fn(),
};
globalServiceMock = {
showToast: jest.fn(),
};
component.ngOnInit();
});
describe('Test: createHero', () => {
it('should create hero success', () => {
const hero = {
name: 'hero name',
shortName: 'hero short name',
capacity: 2,
};
const response = {
name: 'hero name',
shortName: 'hero short name',
capacity: 2,
isActive: true,
id: '622af8e8920cf32bfff17bf1',
};
component.goBack = jest.fn();
component.handleErrors = jest.fn();
component.createHero(hero);
const spygetExpense = jest
.spyOn(heroServiceMock, 'addHero')
.mockReturnValue(of(response));
expect(heroServiceMock.addHero(hero)).toBe(response);
const result = heroServiceMock.addHero(hero);
expect(spygetExpense).toHaveBeenCalledWith(hero);
result.subscribe(
(data) => {
expect(data).toBe(response);
expect(component.goBack).toHaveBeenCalled();
expect(globalServiceMock.showToast).toHaveBeenCalled();
},
(error) => {
expect(component.handleErrors).toHaveBeenCalledWith(error);
}
);
});
});
});
But the the response and error branch still not coverage. And the result.subscribe seems not work. Can you tell me how to change my test?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
