单元测试angularjs - 如何注入服务依赖?

时间:2017-12-12 20:14:18

标签: angularjs unit-testing dependency-injection karma-webpack

我在ThingBuilderService中引入了一个MyDataApiService依赖项,现在ThingBuilderService测试失败了。如何模拟MyDataApiService并在测试中告诉ThingBuilderService?

export default class ThingBuilderService {
    public static $inject = ['MyDataApiService'];

    public myData: any[];

    /**
    * Construct an instance of ThingBuilderService.
    *
    * @param {xyz.MyDataApiService} myDataApiService The MyDataApiService object.
    */
    constructor(myDataApiService: xyz.MyDataApiService) {
        myDataApiService.getSomeData()
        .then((response) => this.myData = response.data);
    }

    //...
}

测试:(我已经包含了代码,显示了我想要我需要做的事情的一部分,但我不明白如何将各个部分组合在一起。

describe('Thing Builder Service', () => {
    var service;
    var mockMyDataApiService = {};

    beforeEach(() => {
        var mockMyDataApiService.getSomeData = () => {
            var deferred = $q.defer();
            deferred.resolve({ data: [
                {
                    'ItemId': 1010101,
                    'Description': 'asdfasdf'
                },
                {
                    'ItemId': 1010102,
                    'Description': 'jkjkjkjk'
                } 
            ]});
            return deferred.promise;
        };

        // *********** now what? ***********
        // and do I have to do something to make '$q' 
        // available in the getSomeData function?

        angular.mock.module('abc.module');
        angular.mock.inject(_ThingBuilderService_ => {
            service = _ThingBuilderService_;
        });    
    });

    // tests here
    it('should ...', () => { ... });
});

测试运行会出现如下错误:

  

错误:[$ injector:unpr]未知提供者:MyDataApiServiceProvider< -   MyDataApiService< - ThingBuilderService

和此:

  

错误:未为MyDataApiService定义基本网址

1 个答案:

答案 0 :(得分:0)

您必须提供您的模拟服务:

angular.mock.module(function($provide) {
  $provide.service(„MyDatApiService“, mockMyDataApiService);
});