angularjs - Jasmine - TypeError : Cannot read property 'spyOn' of null

标签 angularjs unit-testing jasmine

我正在为使用 mocha/jasmine 的服务编写单元测试。我的原始服务依赖于 NodeSrv 服务。但是,当我在单元测试中注入(inject)它时,它看起来并没有真正注入(inject)依赖项 NodeSrv 服务。我得到 TypeError: Cannot read property 'spyOn' of null

describe("Label Exists Check Service", function() {
  var LabelExistsCheck;
  var NodeSvc;
  var VipSvc;

  beforeEach(function() {
    return module("main");
  });

  beforeEach(inject(function(_LabelExistsCheck_, _NodeSvc_, _VipSvc_) {
    LabelExistsCheck = _LabelExistsCheck_;
    NodeSvc = _NodeSvc_;
    VipSvc = _VipSvc_;
  }));

  describe("It should check if node label exists", function() {
    spyOn(NodeSvc, "getNodes").and.returnValue(["testing1", "foo"]);
    newLabelName = "testing1";
    oldLabelName = "nada";


    devices = NodeSvc.getNodes();
    deviceExist =  devices.some(function(element) {
      if (newLabelName == element) {
        return true
      }});

    //spyOn(form, "$setValidity");

    it("node label should already exist and call set form", function() {
      expect(NodeSvc.getNodes).toHaveBeenCalled();
    });
  });
});

更新:

尝试了以下并得到了 TypeError: Cannot read property 'returnValue' of undefined:

describe("Label Exists Check Service", function() {
  var LabelExistsCheck;
  var NodeSvc;
  var VipSvc;

  beforeEach(function() {
    return module("main");
  });

  beforeEach(inject(function(_LabelExistsCheck_, _NodeSvc_, _VipSvc_) {
    LabelExistsCheck = _LabelExistsCheck_;
    NodeSvc = _NodeSvc_;
    VipSvc = _VipSvc_;
  }));

  beforeEach(function() {
    spyOn(NodeSvc, "getNodes").and.returnValue(["testing1", "foo"]);
  });


  it("It should check if node label exists", function() {
    newLabelName = "testing1";
    oldLabelName = "nada";


    devices = NodeSvc.getNodes();
    deviceExist =  devices.some(function(element) {
      if (newLabelName == element) {
        return true
      }});

    //spyOn(form, "$setValidity");

  });
});

最佳答案

.andReturn 的旧语法似乎可以代替。不确定我的系统有什么问题,因为我曾经/仍在使用 Jasmine 2.0。

更新:在测试配置中...即使未安装 jasmine < 2,我也需要指定 jasmine2

关于angularjs - Jasmine - TypeError : Cannot read property 'spyOn' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26457176/

相关文章:

javascript - Jasmine 中使用外部库进行单元测试

javascript - javascript递归调用的问题

angularjs - Visual Studio 中的 Html Angular 智能感知

javascript - AngularJS 使用 UI Router 进行翻译

scala - 如何在 Scala Slick 中模拟数据库

ios - 是否可以使用 Xcode 单元测试执行 GUI 测试

javascript - 无法使用node.js和 Angular 将图像blob上传到AWS S3

javascript - 如何在 Angular JS 中将我的表字符串解析为 html 表?

java - 从 @ComponentScan 中排除测试类中的配置

javascript - 单元测试数组推送