Kieran Wild
Kieran Wild

Reputation: 71

JS unit tests help in karma/Jasmine

I am struggling with this test. I am trying to check that window.location.href changes. So I have mocked window.location.href but no idea how to get the function itself to use the mocked version.

Better to just see the code...

This adds the event listener which triggers the function I am testing: EventListener added to the DOM object earlier in the code.

This is the function I am trying to test: Function which is triggered on click (function I am trying to test)

This is the test I am trying to make work: Test I am trying to make work

Any help would be massively appreciated. Cheers Guys.

Upvotes: 0

Views: 249

Answers (1)

Artsiom Miksiuk
Artsiom Miksiuk

Reputation: 4303

Whenerver you function is declared, you can require this module into your test script and call directly. As far as I see, you function decalred as private function, for internal use only. Usually functional testing, at least unit testing using only public interface to test all unit functionality.

There is two possible solutions.

  1. Make you function public. That means, that you should be able to call this function via direct call on the testing module.
  2. Test this function through another functions. This principle, says, that you can call any public method and it should work properly. It doesn't matter if it actually using this method or not. Final result should be correct. In this case you can try to fire an event that will call you testing method.

And another thing here is that you trying to test code with side effects. It is alwyas hard to test such things. You can try to split-up it several parts and test part that is without side effect, and leave side effect part as simple as possible. Or you can fully mock this function and watch under result change.

Summary: Fire artificial click event, or split up you method on two parts and test one which is without side effects.

Upvotes: 1

Related Questions