admin管理员组

文章数量:1334159

Case

When I create a spy on rootScope, the expectation fails for some reason. Check out the plunkr and try just menting it out and reversing to see.

Code

Plunker Example

describe('Testing', function() {
  var rootScope = null

  //you need to indicate your module in a test
  // beforeEach(module('plunker'));

  beforeEach(inject(function($rootScope, $controller) {
    rootScope = $rootScope;

    rootScope.value = false;

    rootScope.testFn = function() {
      rootScope.value = true;
    }
  }));

  it('should modify root scope', function() {
    // Creating this spy makes test fail
    // Comment it outto make it pass
    spyOn(rootScope, 'testFn');
    expect(rootScope.value).toEqual(false);
    rootScope.testFn();
    expect(rootScope.value).toEqual(true);
  });
});

Case

When I create a spy on rootScope, the expectation fails for some reason. Check out the plunkr and try just menting it out and reversing to see.

Code

Plunker Example

describe('Testing', function() {
  var rootScope = null

  //you need to indicate your module in a test
  // beforeEach(module('plunker'));

  beforeEach(inject(function($rootScope, $controller) {
    rootScope = $rootScope;

    rootScope.value = false;

    rootScope.testFn = function() {
      rootScope.value = true;
    }
  }));

  it('should modify root scope', function() {
    // Creating this spy makes test fail
    // Comment it outto make it pass
    spyOn(rootScope, 'testFn');
    expect(rootScope.value).toEqual(false);
    rootScope.testFn();
    expect(rootScope.value).toEqual(true);
  });
});
Share Improve this question asked Feb 6, 2014 at 22:53 km6zlakm6zla 4,9072 gold badges31 silver badges53 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

You need to tell the spy to do something:

spyOn(rootScope, 'testFn').andCallThrough();

I updated the plnkr here: http://plnkr.co/edit/t3ksMtKSI3CEkCtpZ8tI?p=preview

Hope this helped!

本文标签: javascriptJasmine spyOn scope function breaks testStack Overflow