Home > OS >  Test case for a function call within a function fails in Jasmine/Karma (Angular test cases)
Test case for a function call within a function fails in Jasmine/Karma (Angular test cases)

Time:10-08

I'm learning to write test cases and have been trying to solve old test cases and make them working ,I'm stuck in a particular scenario where in I have a function in angular as below

PasswordBox(): void {
    const dialogRef = this.dialog.open(PasswordComponent, {
      width: '600px',
      data: {
        userDetails: this.userData.email,
      }
    });
    dialogRef.afterClosed().subscribe(result => {
    });
  }

and for the above function in .spec file have written the test case as below

 it('should navigate to create user', fakeAsync(() => {
   fixture.whenStable().then(() => {
    spyOn(component,'PasswordBox').and.callFake;
    expect(dialogSpy).toHaveBeenCalledTimes(1);
    });
  }));

but still when i run the test cases it fails and says Expected spy open to have been called once. It was called 0 times

where is that i'm going wrong I just need to check if the dialog.open has been called inside Passwordbox ,request to please guide if any information is missing please do let me know so I can update the question

have created dialogspy in beforeEach as

dialogSpy = spyOn(component.dialog, 'open').and.callThrough();

CodePudding user response:

I think the problem is in callFake call.

Spies: and.callFake By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function.

So it looks like instead of calling the component.PasswordBox() You are faking the function with callFake, so the real function is never called.

Also callFake accepts methoid as parameter, and You didn't pass anything. https://jasmine.github.io/api/edge/SpyStrategy.html

CodePudding user response:

You install a spy on PasswordBox, so you don't call it.

As a note, I believe .and.callFake cannot be like that but needs a parameter such as .and.callFake(() => { /* do some stuff */ }).

My suggestion would be to use callThrough instead, this way you can at the same time check whether your your PasswordBox method was called and still get the behavior you want to test.

If you don't actually want to open the dialog in your test, you should mock the dialog.open method.

So you could do something like:

const mockDialogRes = ... // whatever your dialog should return
const dialogSpy = spyOn(component.dialog, 'open').and.returnValue({
  afterClosed: of(mockDialogRes),
})
 it('should navigate to create user', fakeAsync(() => {
   fixture.whenStable().then(() => {
    spyOn(component,'PasswordBox').and.callThrough();
    expect(dialogSpy).toHaveBeenCalledTimes(1);
    });
  }));

  • Related