我正试图将卡玛和茉莉花融入我的项目中。
我从一个非常基本的测试开始,以确保定义了我的控制器,并且一个$scope变量等于一个字符串--正如预期的那样通过。
我的控制器,也调用一个执行$http.get的服务,在运行我的测试时,没有提到服务,我得到了错误:
Error: Unexpected request: GET /my/endpoint/
No more request expected
主计长:
define(['module'], function (module) {
'use strict';
var MyController = function ($scope, MyService) {
$scope.testScope = 'karma is working!';
MyService.getData().then(function (data) {
$scope.result = data.hour
});
};
module.exports = ['$scope', 'MyService', MyController ];
});
测试:
define(['require', 'angular-mocks'], function (require) {
'use strict';
var angular = require('angular');
describe("<- MyController Spec ->", function () {
var controller, scope;
beforeEach(angular.mock.module('myApp'));
beforeEach(inject(function (_$controller_, _$rootScope_) {
scope = _$rootScope_.$new();
controller = _$controller_('MyController', {$scope: scope});
scope.$apply();
}));
it('should verify that the controller exists ', function() {
expect(controller).toBeDefined();
});
it('should have testScope scope equaling *karma is working*', function() {
expect(scope.testScope ).toEqual('karma is working!');
});
});
});
是否预期出现上述错误?
以下是答复中的最新情况:
define(['require', 'angular-mocks'], function (require) {
'use strict';
var angular = require('angular');
describe("<- MyController Spec ->", function () {
var controller, scope, $httpBackend, myService;
beforeEach(angular.mock.module('myApp'));
beforeEach(inject(function (_$controller_, _$rootScope_, _$httpBackend_, _myService_) {
scope = _$rootScope_.$new();
$httpBackend = _$httpBackend_;
$httpBackend.expectGET("/my/endpoint");
controller = _$controller_('MyController', {$scope: scope});
scope.$apply();
}));
it('should verify that the controller exists ', function() {
expect(controller).toBeDefined();
});
it('should have testScope scope equaling *karma is working*', function() {
expect(scope.testScope ).toEqual('karma is working!');
});
});
});
发布于 2016-02-25 09:12:30
使用角度莫克斯,如果有一个意外的或不正确的http请求尝试--即使是模板--你总是会得到一个错误。在您的例子中,有两种方法可以用于测试:
使用$httpBackend
$httpBackend
是为测试http请求而设计的,而不需要实际触及线路。在您的测试中,只需添加
$httpBackend.expectGET("/my/endpoint");
在初始化控制器之前。
嘲弄服务
服务本身正在发出http请求,因此您可以代之以模拟服务。服务将像往常一样自动注入,但您可以显式地注入您想要的任何内容:
controller = _$controller_('MyController', {$scope: scope,
MyService: {getData: () => ({then: () => {}}) });
这将注入一个具有getData
函数的对象,该函数返回带有.then
函数的对象。当然,这并不接近于实现您想要做的事情,但这是执行测试的另一种方式。
上述两种方法都是有效的。这取决于您正在测试什么,以及您试图通过测试完成什么。
https://stackoverflow.com/questions/35633680
复制相似问题