user3487327 user3487327 -4 years ago 186
AngularJS Question

Jasmine test case when a function is called in an if statement

I have a function:

function getNames() {
var ids = [];
var checkAttr = function (array, attr, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][attr] === value) {
return false;
return true;
for (var i = 0; i < result.length; i++) {
var selected = result[i];
if (checkAttr($scope.names, "name", && ids.indexOf( === -1 && selected.myInfo && !== "") {

I want to write a test that checks that I am using the checkAttr function to check both name and id to remove duplicates. But I am not sure how to. I tried using spyOn but kept getting errors.

I want something that reads like this:

it('should check the name and id to remove duplicates', function() {
//do something here

Answer Source

It's impossible to mock that method without changing your code.

I think It would be a bad test if you could spy a private function. Usually your tests mustn't know about inner implementation of your functions because if you change inners you must change your tests. It's a bad practice. In your case you should test the function getNames like a black box by setting $scope.names and checking a result from $scope.fundNames after it's call.

But you can move checkAttr function outside and spyOn it to achieve your testcase.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download