【发布时间】: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