Reputation: 21
I am new Angular test case. And struck with loading JSON via HTTP call.
We can call static method using spyOn but I could not figure out how to inject HTTP and load json and subscribe there
I really need help!! And Thanks a lot in advance
Upvotes: 0
Views: 324
Reputation: 201
It looks like you are approaching the problem in the wrong way. You should mock the method in "load-json.service.ts", the mocked method should return the exact JSON
If you are testing some components, the following is what I am suggesting.
Notice in the providers, we are forcing the component to use our mocked LoadJsonService.
...
const jsonDataObj = {foo: 'bar'};
const mockedLoadJsonService = {
getJson:()=> JSON.stringify(jsonDataObj)
}
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
...
],
declarations: [...],
providers: [
{ provide: LoadJsonService, useValue: mockedLoadJsonService },
],
}).compileComponents();
});
...
Upvotes: 0
Reputation: 2072
I can give you an example from my project. Maybe it will help you to get an idea.
describe("Interviews service", () => {
let httpClientSpy: jasmine.SpyObj<HttpClient>;
let interviewsService: InterviewsService;
beforeEach(() => {
const apiUrlsServiceFake = jasmine.createSpyObj('ApiUrlsBuilderService', ['getApiUrl']);
httpClientSpy = jasmine.createSpyObj('HttpClient', ['post']);
interviewsService = new InterviewsService(httpClientSpy, apiUrlsServiceFake);
});
it('should create new interview and return new interview data', (done: DoneFn) => {
const expectedNewInterviewData: NewInterviewData = { id: 1234, encodedId: "qweasd" };
httpClientSpy.post.and.returnValue(asyncData(expectedNewInterviewData));
interviewsService.createNewInterview(1111, "New interview").subscribe({
next: newIwData => {
expect(newIwData).withContext("Expect new interview data").toEqual(expectedNewInterviewData);
done();
},
error: done.fail
});
expect(httpClientSpy.post.calls.count()).withContext('one call').toBe(1); }); });
Upvotes: 0