相关疑难解决方法(0)

从服务器获取数据的推荐方法

在不使用的情况下,在AngularJS中连接到服务器数据源的建议方法是什么$resource.

$resource有很大的局限性,如:

  1. 没有使用适当的未来
  2. 不够灵活

angularjs

145
推荐指数
2
解决办法
6万
查看次数

将模拟注入AngularJS服务

我写了一个AngularJS服务,我想对它进行单元测试.

angular.module('myServiceProvider', ['fooServiceProvider', 'barServiceProvider']).
    factory('myService', function ($http, fooService, barService) {

    this.something = function() {
        // Do something with the injected services
    };

    return this;
});
Run Code Online (Sandbox Code Playgroud)

我的app.js文件已注册:

angular
.module('myApp', ['fooServiceProvider','barServiceProvider','myServiceProvider']
)
Run Code Online (Sandbox Code Playgroud)

我可以测试DI是这样工作的:

describe("Using the DI framework", function() {
    beforeEach(module('fooServiceProvider'));
    beforeEach(module('barServiceProvider'));
    beforeEach(module('myServiceProvder'));

    var service;

    beforeEach(inject(function(fooService, barService, myService) {
        service=myService;
    }));

    it("can be instantiated", function() {
        expect(service).not.toBeNull();
    });
});
Run Code Online (Sandbox Code Playgroud)

这证明了服务可以由DI框架创建,但是接下来我想对服务进行单元测试,这意味着模拟注入的对象.

我该怎么做呢?

我已经尝试将模拟对象放在模块中,例如

beforeEach(module(mockNavigationService));
Run Code Online (Sandbox Code Playgroud)

并将服务定义重写为:

function MyService(http, fooService, barService) {
    this.somthing = function() {
        // Do something with the injected services
    };
});

angular.module('myServiceProvider', …
Run Code Online (Sandbox Code Playgroud)

javascript mocking jasmine angularjs angularjs-service

114
推荐指数
1
解决办法
10万
查看次数