I am new to angular and unit testing, I am trying to write a unit test for the component with service where the service url is fetched from the @Input()
value.
cms-sonor.component.ts
export class CmsSonarComponent implements OnInit {
@Input() configParam;
sonarData;
constructor(public cmsService: CmsService) {}
ngOnInit(): void {
this.cmsService
.getData(this.configParam.url, { responseType: "text" })
.subscribe(
(resp) => {
this.sonarData = resp;
},
(err) => {
console.log(err);
}
);
}
}
cms-sonar.component.spec.ts
describe("CmsSonarComponent", () => {
let component: CmsSonarComponent;
let injector: TestBed;
let fixture: ComponentFixture<CmsSonarComponent>;
let service: CmsService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [CmsSonarComponent, SonorPipe],
providers: [
{
provide: CmsService,
useValue: {
getData: () => of({ id: 123, name: "Product" }),
},
},
],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CmsSonarComponent);
service = TestBed.get(CmsService);
component = fixture.componentInstance;
//fixture.detectChanges();
});
it("should create", () => {
expect(component).toBeDefined();
});
it("testing cms sonar ngOnInit", () => {
spyOn(service, "getData").and.callThrough();
component.ngOnInit();
fixture.detectChanges();
expect(service.getData).toHaveBeenCalledWith("/getData", "json");
expect(component.sonarData).toEqual({ id: 123, name: "Product" });
});
});
Error
TypeError: Cannot read property 'url' of undefined
Can you let me known what mistake I am making? Any help is appreciated.
i even try with args like this spyOn(service, 'getData') .withArgs('abc')
Update-1 I was able resolve the above issue, URL was try to getting the input value.
const configParam = {
url: 'visible'
};
beforeEach(() => {
fixture = TestBed.createComponent(CmsSonarComponent);
service = TestBed.get(CmsService);
component = fixture.componentInstance;
component.configParam = configParam;
//fixture.detectChanges();
});
it('testing cms sonar ngOnInit', () => {
spyOn(service, 'getData').and.callThrough();
component.ngOnInit();
fixture.detectChanges();
expect(service.getData).toHaveBeenCalledWith('visible', {
responseType: 'text'
});
expect(component.sonarData).toEqual({ id: 123, name: 'Product' });
});
But now i am get this error
Expected spy getData to have been called with:
[ 'visible', Object({ responseType: 'text' }) ]
but actual calls were:
[ 'visible' ],
[ 'visible' ]
any guides on this is highly appreciated.