Home > Net >  In Angular test case, Make static method call from a service where HTTP get will load json which is
In Angular test case, Make static method call from a service where HTTP get will load json which is

Time:02-23

I am new Angular test case. And struck with loading JSON via HTTP call.

  • So basically from a service spec file: "url-service.spec" it calls a static method which is in another service: "load-json.service.spec".
  • Here in "load-json.pservice.spec" it makes HTTP get call to load json and also subscribes there itself and then returns only JSON. [NOTE: It doesn't return observable back to url-service].

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

CodePudding user response:

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);   });   });

CodePudding user response:

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();
  });

...

  • Related