Jasmine - TypeError:无法读取属性' spyOn'为null

时间:2014-10-20 01:05:36

标签: angularjs unit-testing jasmine

我正在为mocha / jasmine的服务编写单元测试。我的原始服务取决于NodeSrv服务。但是,当我在单元测试中注入它时,它看起来并不真正注入依赖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");

  });
});

1 个答案:

答案 0 :(得分:6)

.andReturn的旧语法似乎有效。不知道我的系统中有什么坏了,因为我现在/仍在使用Jasmine 2.0。

更新:在testem配置中......我需要指定jasmine2即使jasmine< 2未安装。