如何从Angular.js模块获取资源进行茉莉花测试 [英] How do I get a resource from an Angular.js module for a jasmine test
问题描述
我有一个包含项目资源的模块,代码如下:
I have a module that contains resources for a project, and the code looks like this:
editor_services.js
var editorServices = angular.module('editorServices', ['ngResource']);
editorServices.factory('Project', ['$resource', '$http',function($resource, $http){
//...etc
现在,我想为期望项目资源作为参数的控制器编写测试.如何从editorServices
变量中获取由该工厂创建的项目资源的实例?
now I would like to write tests for a controller that expects a project resource as an argument. How can I get an instance of the project resource that is created by this factory out of the editorServices
variable?
推荐答案
下面是一个有效的示例,该示例将如何以角度测试资源(或http) http://plnkr.co/edit/kK5fDFIVpyZTInH1c6Vh?p=preview
Here is a working example how one would test Resources (or http) in angular http://plnkr.co/edit/kK5fDFIVpyZTInH1c6Vh?p=preview
基本设置是:
-
在测试中
-
加载
angular-mocks.js
.这将$httpBackend
替换为模拟版本.请参阅: http://docs.angularjs.org/api/ngMock .$ httpBackend
load
angular-mocks.js
in your test. This replaces the$httpBackend
with mock version. See: http://docs.angularjs.org/api/ngMock.$httpBackend
在测试调用$httpBackend.expect()
中创建要被模拟的期望.
In your test call $httpBackend.expect()
to create expectation to be mocked out.
要模拟服务器响应时,请调用$httpBackend.flush()
When you want to simulate server response call $httpBackend.flush()
有一个警告,茉莉花的普通.toEqual()
不能与$resource
配合使用,因此您必须像这样创建自定义匹配器:
There is a caveat that normal .toEqual()
from jasmine dose not work with $resource
so you have to create custom matcher like so:
beforeEach(function() {
this.addMatchers({
// we need to use toEqualData because the Resource hase extra properties
// which make simple .toEqual not work.
toEqualData: function(expect) {
return angular.equals(expect, this.actual);
}
});
});
这篇关于如何从Angular.js模块获取资源进行茉莉花测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!