javascript - Jasmine spyOn 范围函数中断测试

标签 javascript angularjs jasmine

案例

当我在 rootScope 上创建一个 spy 时,期望由于某种原因失败了。查看 plunkr 并尝试将其注释掉并反向查看。

代码

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);
  });
});

最佳答案

你需要告诉 spy 做一些事情:

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

我在这里更新了 plnkr:http://plnkr.co/edit/t3ksMtKSI3CEkCtpZ8tI?p=preview

希望这对您有所帮助!

关于javascript - Jasmine spyOn 范围函数中断测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21615847/

相关文章:

javascript - 视觉 : Table filter on column name with condition

angularjs - 所见即所得的 Angular2 和双向绑定(bind)

javascript - 使用 Jasmine 监视函数中的变量

javascript - 错误 TS2304 : Cannot find name 'createNewEvent'

javascript - facebook 是否喜欢按钮容易受到点击劫持?

javascript - Fabric.js - 在选定对象下移动对象

javascript - jQuery 按类隐藏元素并不隐藏所有元素

angularjs - Identity Server 身份验证无需请求用户许可

javascript - 响应类型为 text/plain 的 Angular 资源总是生成一个字符串数组

Javascript Kriskowal Q JS promise 不起作用