在查询$httpBackend后我似乎无法返回预期的结果,我不知道测试有什么问题.你能看看这个失败的最小例子吗?
链接演示
http://jsfiddle.net/paos/kTNF5/
茉莉花输出
query() Expected [ ] to equal [ { hello : 'world' } ].
码
依赖资源
<script src="https://raw.github.com/pivotal/jasmine/master/lib/jasmine-core/jasmine.js"></script> <script src="https://raw.github.com/pivotal/jasmine/master/lib/jasmine-core/jasmine-html.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular-resource.min.js"></script> <script src="http://code.angularjs.org/1.0.1/angular-mocks-1.0.1.js"></script>
测试javascript
var mod = angular.module('mod',['ngResource']); mod.factory('Brief',function($resource) { var Brief = $resource('http://some_test/:id'); return Brief; }); beforeEach(function() { module('mod'); inject(function($injector) { resource = $injector.get('$resource'); $httpBackend = $injector.get('$httpBackend'); Brief = $injector.get('Brief'); }); }); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); describe("Brief",function() { it("query()",function() { var getRequest = 'http://some_test'; var fakeGetResponse = [{ "hello": "world"}]; $httpBackend.when('GET',getRequest).respond(fakeGetResponse); var briefs = Brief.query(); expect(briefs).toEqual(fakeGetResponse); $httpBackend.flush(); }); }); // KICK OFF JASMINE var jasmineEnv = jasmine.getEnv(); var trivialReporter = new jasmine.TrivialReporter(); jasmineEnv.addReporter(trivialReporter); jasmineEnv.specFilter = function(spec) { return trivialReporter.specFilter(spec); }; jasmineEnv.execute();
谢谢!
你几乎就在那里,但你的测试中仍有2个问题:
原文链接:https://www.f2er.com/angularjs/141366.html>在$httpBackend被刷新之前验证了期望.它是$httpBackend.flush();模拟传入的响应
>在您的期望中,您正在比较对象实例(而不是它们的值),但AngularJS $资源将创建一个新数组,如https://stackoverflow.com/a/11966512/1418796中所述.您需要比较对象的值而不是引用.这样做的一种方法是:expect(angular.equals(briefs,fakeGetResponse)).toBeTruthy();
最后这里有一个测试传递的jsFiddle:http://jsfiddle.net/VFqFU/