【发布时间】:2014-07-15 23:40:04
【问题描述】:
我对 Angular \SinonJS 有点陌生,所以请原谅这个愚蠢的问题,如果这很明显,请耐心等待。我做了一些谷歌搜索,似乎找不到答案。我使用 SinonJs 进行模拟,正如 Pluralsight 视频中推荐的那样。不确定它是否是最佳选择。欢迎任何替代品。
我想测试我的 AngularJS 控制器的行为并测试它是否使用我只指定一次的条件调用我的存储库搜索方法。
我的控制器中有以下内容,我的 Jasmin 测试运行程序中出现错误:
目标控制器.js:
stepByStepApp.controller("goalController", function ($scope, goalRepository) {
$scope.viewGoalButtonDisabled = true;
$scope.search = function (criteria) {
$scope.errors = [];
return goalRepository.search(criteria).$promise.then(
function (goals) {
$scope.viewGoalButtonDisabled = true;
return goals;
},
function (response) {
$scope.viewGoalButtonDisabled = true;
$scope.errors = response.data;
});
};
});
目标控制器测试.js
'use strict';
(function () {
describe('Given a Goal Controller', function () {
var scope, controller, goalRepositoryMock, goals, criteria;
beforeEach(function () {
module('stepByStepApp');
inject(function ($rootScope, $controller, goalRepository) {
scope = $rootScope.$new();
goalRepositoryMock = sinon.mock(goalRepository);
goals = [{ foo: 'bar' }];
criteria = 'test search criteria';
controller = $controller('goalController', { $scope: scope });
});
});
it('the View Goal Button should be disabled', function () {
expect(scope.viewGoalButtonDisabled).toBe(true);
});
describe("when a goal is searched for, it", function () {
it("should search the Goal Repository", function () {
goalRepositoryMock.expects('search').once().returns(goals);
scope.search(criteria);
goalRepositoryMock.verify();
});
});
});
}())
我收到以下错误:
2 specs, 1 failure
Given a Goal Controller
when a goal is searched for, it
should search the Goal Repository
TypeError: Cannot read property 'then' of undefined
我显然没有正确地嘲笑对“goalRepository.search(criteria).$promise.then”的调用。如何正确模拟 $promise 和 .then ?提前致谢。
【问题讨论】:
标签: angularjs mocking jasmine sinon