Cannot successfully test my NgForm call with Angular2+

71 Views Asked by At

I am attempting to test whether I can login successfully by sending in username & password inputs through an NgForm, but I cannot seem to get through successfully... Is there something I am missing?

I am currently getting the error:

Chrome 67.0.3396 (Mac OS X 10.13.5) LoginComponent should call auth.login when passed a valid form with correct credentials onSubmit FAILED
    Expected spy login to have been called.
        at UserContext.<anonymous> src/app/components/login/login.component.spec.ts:87:26)
        at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:388:1)
        at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke node_modules/zone.js/dist/zone-testing.js:288:1)
        at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:387:1)
1

There are 1 best solutions below

2
physicsboy On

The solution I came across with much help from @trichetriche was the need for a return on my spyOn.

I also needed to add the valid: true option to my NgForm json that is to be passed through:

const validFormGoodCreds = <NgForm>{
    valid: true,
    value: {
      username: "someUsername",
      password: "somePassword"
    }
  };

Since I didn't care about what was returned currently and only want to focus on whether the function is called or not, I opted for the solution of changing the line:

authLoginSpy = spyOn(component['authService'], 'login');

to

authLoginSpy = spyOn(component['authService'], 'login').and.callThrough();

This can then see that the function should be run fully and therefore will hit the call to login().