问题
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
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?
回答1:
Here is a working example how one would test Resources (or http) in angular http://plnkr.co/edit/kK5fDFIVpyZTInH1c6Vh?p=preview
The basic setup is:
load
angular-mocks.js
in your test. This replaces the$httpBackend
with mock version. See: http://docs.angularjs.org/api/ngMock.$httpBackendIn your test call
$httpBackend.expect()
to create expectation to be mocked out.When you want to simulate server response call
$httpBackend.flush()
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); } }); });
来源:https://stackoverflow.com/questions/16486115/how-do-i-get-a-resource-from-an-angular-js-module-for-a-jasmine-test