单位测试:
"use strict"; var usersJSON = {}; describe("mainT",function () { var ctrl,scope,httpBackend,locationMock,beforeEach(module("testK")); beforeEach(inject(function ($controller,$rootScope,$httpBackend,$location,$injector) { scope = $rootScope.$new(); httpBackend = $httpBackend; locationMock = $location; var lUrl = "../solr/users/select?indent=true&wt=json",lRequestHandler = httpBackend.expect("GET",lUrl); lRequestHandler.respond(200,usersJSON); ctrl = $controller("mainT.controller.users",{ $scope: scope,$location: locationMock}); httpBackend.flush(); expect(scope.users).toBeDefined(); })); afterEach(function () { httpBackend.verifyNoOutstandingRequest(); httpBackend.verifyNoOutstandingExpectation(); }); describe("method test",function () { it('should test',function () { expect(true).toBeFalsy(); }); }); });
控制器我正在测试(工作):
init中的Asynchrone函数给我带来麻烦(使用../solr/users/select?indent=true\u0026amp;wt=json):
$scope.search = function () { var lStart = 0,lLimit = privates.page * privates.limit; Search.get({ collection: "users",start: lStart,rows: lLimit) },function(records){ $scope.users= records.response.docs; }); };
我认为发生了什么:
1.告知后端他将收到什么请求
2.通过空JSON通知后端对该请求的响应
3.创建一个控制器(Search.get get执行)
4.通知后端接收所有请求并回答(冲洗)
但我总是得到以下错误:
Error: Unexpected request: GET : ../solr/users/select?indent=true&wt=json
我不是很好地处理异步检索功能吗?该怎么做?
解决方法
在BeforeEach中,您应该使用httpBackend.when而不是httpBackend.expect.我不认为你的BeforeEach中应该有一个断言(expect),所以应该将它移到一个单独的it()块中.我也没有看到lRequestHandler的定义.默认情况下会发送200状态,因此不需要.您的httpBackend行应如下所示:
httpBackend.when("GET","/solr/users/select?indent=true&wt=json").respond({});
那么你的测试应该是:
describe("method test",function () { it('scope.user should be defined: ',function () { expect(scope.user).toEqual({}); }); });