I am trying to write unit test cases using jasmine. I have a scenario where I am passing data to function with different properties I just want to check if that function is getting executed successfully or with out any error. I tried expect(foo).toHaveBeenCalled()
but it expects a spy instead of a function. Please suggest any way to write a test case expectation in this scenario.
Asked
Active
Viewed 1,393 times
1

Sonali
- 2,223
- 6
- 32
- 69
2 Answers
1
toHaveBeenCalled()
can be used only with the spy
.
Create a spy
on your method and try this
spyOn(obj, 'foo');
obj.foo(); // call foo()
expect(obj.foo).toHaveBeenCalled()

Amit Chigadani
- 28,482
- 13
- 80
- 98
-
1What is `obj` wrt original question? Also, the test makes little sense. `obj.foo` obviously has been called the line above the assertion :) – Yury Tarabanko Jul 24 '18 at 11:52
-
Forgive me. This is very much w.r.t angular as opposed to angularjs. I thought it to be the same. – Amit Chigadani Jul 24 '18 at 11:55
0
What are you trying to test, exactly?
Test that
foo
is working correctly. In that case, just callfoo()
from your test. If it throws, the test will fail.Test that some other function
bar
is working correctly, where "correctly" means that it should callfoo
. In that case, create a spy forfoo
and usetoHaveBeenCalled()
on the spy. This may require that you restructure your code so you can somehow inject thefoo
spy intobar
.
From your description, it seems that you want both at the same time, which goes against the principle of unit testing: you test one thing at a time.

Thomas
- 174,939
- 50
- 355
- 478