我是Angular \ SinonJS的新手,所以请原谅这个愚蠢的问题,如果这很明显,请耐心等待。我已经进行了一些谷歌搜索,但似乎找不到答案。正如Pluralsight视频中所建议的那样,我已经使用SinonJs进行了模拟。不确定是否是最佳选择。任何替代的欢迎。
我想测试我的AngularJS控制器的行为,并测试它使用仅指定一次的条件调用存储库Search方法。
我的控制器中包含以下内容,并且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;
});
};
});
目标控制器tests.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?提前致谢。
我假设此存储库正在返回资源对象。话虽如此,这就是我将如何测试该控制器的方法。
这是工作中的小伙伴。
您需要模拟承诺链。为此,您需要注入$ q服务。下面是我的全班级beforeEach语句的范围。我使用存根进行嘲笑。我将该模拟程序注入到正在测试的控制器中。
beforeEach(inject(function($controller, $rootScope, $q) {
q = $q
scope = $rootScope;
goalRepositoryStub = sinon.stub({
search: function() {}
});
testCtrl = $controller("goalController", {
$scope: scope,
goalRepository: goalRepositoryStub
});
}));
有了这个模拟的存储库,我现在可以完全控制它的功能。
在这一部分中,我实际上模拟了整个Promise链。我从q服务获得了一个延迟对象。从中我得到一个诺言。然后,我将那个承诺放在一个伪造的资源对象中。然后,无论何时调用搜索,我都会返回该伪造的资源对象。然后,我将搜索范围称为。
beforeEach(function() {
deferred = q.defer();
promise = deferred.promise;
returnedResource = {
$promise: promise
};
goalRepositoryStub.search.returns(returnedResource);
scope.search(criteria);
});
对于实际测试,您需要告诉该延迟对象该做什么(拒绝或解决promise)并触发作用域$ apply()函数。然后,您进行测试以查看您的代码是否正在执行应做的事情。
这是我如何测试对goalRepository的成功调用的示例:
describe('successful goalRepository call', function() {
beforeEach(function() {
deferred.resolve(dataToReturn);
scope.$apply();
});
it('should add the data to scope.goals.', function() {
expect(scope.goals).toBe(dataToReturn);
});
it('should not change scope.failureApi to true.', function() {
expect(scope.viewGoalButtonDisabled).toBeFalsy();
});
});
这些不是必要的“最佳实践”或其他任何东西。这是我发现自己解决此特定问题的一种方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句