我将代码放在小提琴中,以便在需要时可以轻松更新和“使用”。
describe('PlayersListCtrl', function() { // Jasmine Test Suite
beforeEach(module('wc2014App'));
var ctrl, scope, $httpBackend;
beforeEach(inject(function($controller, $rootScope) {
scope = $rootScope.$new();
ctrl = $controller('PlayersListCtrl', {
$scope: scope
});
}));
it('should have an empty player array', function() {
expect(scope.players.length).toBe(0);
});
describe('PlayersListCtrl', function() {
var $httpBackend, $rootScope, createController;
beforeEach(inject(function($injector) {
$httpBackend = $injector.get('$httpBackend');
$httpBackend.when('GET', '../app/stubs/players.json').respond(
{userId: 'userX'},
{'A-Token': 'xxx'});
$rootScope = $injector.get('$rootScope');
var $controller = $injector.get('$controller');
createController = function() {
return $controller('PlayersListCtrl', {'$scope' : $rootScope });
};
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should fetch authentication token', function() {
$httpBackend.expectGET('../app/stubs/players.json');
var controller = createController();
$httpBackend.flush();
});
});
});
其余的,因为它非常冗长,在小提琴中:http: //jsfiddle.net/tLte2/
基本上第一个测试通过了,不是很难,但第二个测试依赖于 JSON 存根并给出如下错误: PhantomJS 1.9.7 (Mac OS X) PlayersListCtrl PlayersListCtrl 应该获取身份验证令牌 FAILED Error: No pending request to flush !
似乎无法掌握这种 $httpBackend
僵硬的工作原理。是否必须可以触发它并将结果设置在控制器的范围内?
--edit 基本上把所有东西都完美地连接起来,可以做一些运行良好的简单测试,但是在那里获取 JSON 存根数据似乎很痛苦。解决方法可以只是在控制器范围内定义 JSON 中描述的数组,例如:controller.players = ['one','two','three',..... etc ......]
但这感觉不对。那$httpBackend
东西应该不难修复吧?