karma/angularjs如何使用服务测试运行块
这篇文章如下 我已经发布了另一个更简单的帖子 范例 要测试的代码 测试 这给了我这个错误karma/angularjs如何使用服务测试运行块,angularjs,karma-runner,angular-mock,Angularjs,Karma Runner,Angular Mock,这篇文章如下 我已经发布了另一个更简单的帖子 范例 要测试的代码 测试 这给了我这个错误 **Error: Unexpected request: GET menus.json No more request expected** 最后请看@scarIz的回复 出现错误的原因是,菜单.query将在您对myApp模块执行每个测试之前运行,因为它在模块的.run()配置中被调用。虽然您已经在运行测试套件中提供了后端定义,但您还没有为MainCtrl提供后端定义 因此,为了解决这一问题,您可能希望
**Error: Unexpected request: GET menus.json
No more request expected**
最后请看@scarIz的回复
出现错误的原因是,
菜单.query
将在您对myApp
模块执行每个测试之前运行,因为它在模块的.run()
配置中被调用。虽然您已经在运行测试套件中提供了后端定义,但您还没有为MainCtrl
提供后端定义
因此,为了解决这一问题,您可能希望使用在每次测试之前运行的全局beforeach
块,该块应在规范之前包含的帮助文件中定义:
beforeEach(inject(function($httpBackend) {
$httpBackend.when('GET', 'menus.json').respond([{id: 1, name: 'Bob'}])
$httpBackend.flush();
}));
@斯卡尔兹非常感谢:)很抱歉打扰你,你能看一看测试结果吗?我应用了相同的代码,但在ui路由器上它不工作,我想知道如何修复它^^
**Error: Unexpected request: GET menus.json
No more request expected**
beforeEach(module('myApp'));
var $httpBackend;
beforeEach(inject(function( _$httpBackend_) {
$httpBackend = _$httpBackend_;
$httpBackend.when('GET', 'menus.json').respond([{
id: 1,
name: 'Bob'
}])
$httpBackend.flush();
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
describe('Init', function() {
describe('MainCtrl', function(){
var scope, $httpBackend,$rootScope;//we'll use these in our tests
//mock Application to allow us to inject our own dependencies
//mock the controller for the same reason and include $rootScope and $controller
beforeEach(inject(function( $controller,_$rootScope_, _$httpBackend_){
$httpBackend = _$httpBackend_;
$httpBackend.when('GET', 'users.json').respond([{
id: 1,
name: 'Bob'
}, {
id:2,
name: 'Jane'
}]);
$rootScope = _$rootScope_;
//create an empty scope
scope = _$rootScope_.$new();
//declare the controller and inject our empty scope
$controller('MainCtrl', {
$scope: scope
});
$httpBackend.flush();
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should have variable text = "Hello World!"', function(){
expect(scope.text).toBe('Hello World!');
});
it('should fetch list of users', function(){
expect(scope.users.length).toBe(2);
expect(scope.users[0].name).toBe('Bob');
expect( $rootScope.valueSetInRun ).toBe(555);
console.log($rootScope.menus);
});
});
});
beforeEach(inject(function($httpBackend) {
$httpBackend.when('GET', 'menus.json').respond([{id: 1, name: 'Bob'}])
$httpBackend.flush();
}));