Home > Software design >  fake http response in ionic and angular when function is called
fake http response in ionic and angular when function is called

Time:01-11

I'm a beginner in jasmine karma test. I'm trying to test a function making an http request. with the script i currently have when i run the test, all is see is the loader and it never gets off the screen. I'd like to know how i can fake a response when the function is called so the loader can be hidden

function

    async login() {
const loader = await this.loadingCtrl.create({
  message: 'Testing',
});
loader.present();
    const payload = {
      username: 'username',
      password: 'test'
    };
    this.userService.login(payload).subscribe((response) => {
      loader.dismiss();
      if (response) {
    
        this.router.navigate(['/user-home']);
      }
    }, err => {
      loader.dismiss();
      this.alertS.show(err, 'OK');
    });
  }

Test Case

  it('should login', () => {
    component.login();
    expect(component.login).toHaveBeenCalled();
  });

CodePudding user response:

You need to mock the service and any dependencies your component might have. You can use createSpyObj from jasmine like the following:

const mockService = jasmine.createSpyObj<UserService>('UserService', ['login']);

// provide a mocking/fake value to be returned by this dependency
beforeEach(() => mockService.login.and.returnValue(of('My value')));

beforeEach(async () => {
 await TestBed.configureTestingModule({
    declarations: [...],
    // configure the dependency within providers
    providers: [{ provide: UserService, useValue: mockService }]
  })
})


it('calls login', () => {
  component.login();

  expect(mockService.login).toHaveBeenCalled();
});

CodePudding user response:

Completely untested but at a guess, since your function is async try something like this:

it('calls login', (done) => {
  await component.login();

  expect(mockService.login).toHaveBeenCalled();

  done();
});
  • Related