【问题标题】:Jasmine testing multiple spies茉莉花测试多个间谍
【发布时间】:2014-03-18 01:44:23
【问题描述】:

我正在为一个 Angular 应用程序编写一些测试,这是我第一次尝试使用 Jasmine 对 Angular 进行单元测试。我在构建测试以适应函数内部的各种场景(即 if 语句和回调)时遇到问题。

这是我的 $scope 函数,它接受一个 Object 作为参数,如果该对象有一个 id,那么它会更新该对象(因为它已经存在),否则它会创建一个新报告并推送到使用CRUD 服务的后端。

$scope.saveReport = function (report) {
  if (report.id) {
    CRUD.update(report, function (data) {
      Notify.success($scope, 'Report updated!');
    });
  } else {
    CRUD.create(report, function (data) {
      $scope.report = data;
      Notify.success($scope, 'Report successfully created!');
    });
  }
};

到目前为止,我的测试通过了一个带有id 的假对象,因此它将触发CRUD.update 方法,然后我检查它是否被调用。

describe('$scope.saveReport', function () {
  var reports, testReport;
  beforeEach(function () {
    testReport = {
      "id": "123456789",
      "name": "test"
    };
    spyOn(CRUD, 'update');
    $scope.saveReport(testReport);
  });
  it('should call CRUD factory and update', function () {
    expect(CRUD.update).toHaveBeenCalledWith(testReport, jasmine.any(Function));
  });
});

我了解 Jasmine 不允许多个间谍,但我希望能够以某种方式测试 if 条件,并在对象 传入对象时运行模拟测试太:

describe('$scope.saveReport', function () {
  var reports, testReport;
  beforeEach(function () {
    testReport = {
      "id": "123456789",
      "name": "test"
    };
    testReportNoId = {
      "name": "test"
    };
    spyOn(CRUD, 'update');
    spyOn(CRUD, 'create'); // TEST FOR CREATE (NoId)
    spyOn(Notify, 'success');
    $scope.saveReport(testReport);
    $scope.saveReport(testReportNoId); // TEST FOR NO ID
  });
  it('should call CRUD factory and update', function () {
    expect(CRUD.update).toHaveBeenCalledWith(testReport, jasmine.any(Function));
    // UNSURE ON THIS PART TOO
  });
});

我已经阅读了有关使用 .andCallFake() 方法的内容,但我看不出这如何与我的设置一起使用。任何帮助都非常感谢。

【问题讨论】:

  • 你试过替代语法jasmine.createSpy() 吗?
  • Jasmine 2 增加了在测试期间重置间谍的能力,这可以满足您的需求吗?在之前的版本中,我只是为其他情况创建了单独的测试。

标签: javascript angularjs unit-testing jasmine


【解决方案1】:

看来你应该先决定你需要测试什么。如果您只想测试在 id 存在时调用 update 或在不存在时调用 create ,那么您应该使用这些条件构造 it 函数。对于其中一些内容,每个之前的位置都是错误的。

it('should call CRUD factory and update', function () {
    spyOn(CRUD, 'update');
    $scope.saveReport(testReport);
    expect(CRUD.update).toHaveBeenCalledWith(testReport, jasmine.any(Function));
});
it('should call CRUD create', function() {
    spyOn(CRUD, 'create');
    $scope.saveReport(testReportNoId); // TEST FOR NO ID
    expect(CRUD.create).toHaveBeenCalledWith(testReport, jasmine.any(Function));
});

只在每次测试之前把你真正应该做的事情放在前面。

希望这有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多