gpt4 book ai didi

angularjs - Jasmine 和 angularjs,不能为服务 stub $httpBackend

转载 作者:行者123 更新时间:2023-12-03 18:25:57 25 4
gpt4 key购买 nike

stubbing $httpBackend 后好像无法返回预期的结果,不知道测试有什么问题。你能看看这个失败的最小例子吗?

与演示链接

http://jsfiddle.net/paos/kTNF5/

Jasmine 输出

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 个问题:

  • 预期在$httpBackend之前得到验证脸红了。它是 $httpBackend.flush();模拟传入响应
  • 在您的期望中,您正在比较对象实例(而不是它们的值)但 AngularJS $resource将创建一个新数组,如 https://stackoverflow.com/a/11966512/1418796 中所述.您需要比较对象的值而不是引用。这样做的一种方法是:expect(angular.equals(briefs, fakeGetResponse)).toBeTruthy();

  • 最后这里是一个 jsFiddle,测试通过: http://jsfiddle.net/VFqFU/

    关于angularjs - Jasmine 和 angularjs,不能为服务 stub $httpBackend,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13667841/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com