I have a Jest test case where I am calling a method inside the angular component. That method has a service call. But somehow I am not able to mock the response object of service
app.component.ts
someMethod() {
try {
this.appService.test().then((response) => {
//I want JEST to execute some logic here after response
}
}
catch (e) {
//JEST always going in this block while testing
}
}
app.component.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BrowserModule } from '@angular/platform-browser';
import {appService} from "./appService";
import { appComponent } from './app.component';
import { HttpClient } from '@angular/common/http';
describe('appComponent', () => {
let component: appComponent;
let fixture: ComponentFixture<appComponent>;
let MockappService : appService;
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
class mockServiceClass {
test(): any {
return { data: {}, status: 200, statusText: 'OK', headers: {}, config: {} }
}
}
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ appComponent ],
schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA],
providers: [{ provide: appService, useClass: mockServiceClass}],
imports: [HttpClientTestingModule, BrowserModule]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(appComponent);
component = fixture.componentInstance;
httpClient = TestBed.inject(HttpClient);
httpTestingController = TestBed.inject(HttpTestingController);
MockappService = TestBed.inject(appService);
// this fixture.detectChanges will kick off the ngOnInit
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
describe('On value change', () => {
it('should validate the form', () => {
component.someMethod();
expect(component.someVariable).toBe("This");
})
});
});
Whenever someMethod()
is getting called from the jest spec file, I want the service to be executed with some valid response object. But, Somehow it is always executing catch block.
Looks like your mock you return the value, whereas a Promise is expected.
Try to wrap the value with
Promise.resolve
: