简体   繁体   English

单元测试具有依赖性的角度服务

[英]Unit testing angular service with dependencies

I have the following Jasmine unit test: 我有以下Jasmine单元测试:

describe('myService', function () {
    var myService, $q;

    // Instantiate the app
    beforeEach(module('myApp'));

    beforeEach(inject(function (_myService_, fileSystemService, $q) {
        myService = _myService_;
        spyOn(fileSystemService, 'listFiles').and.callFake(function () {
            var deferred = $q.defer();
            deferred.resolve('mockresult');
            return deferred.promise;
        });
    }));

    it('checks the number of outbound files', inject(function ($rootScope) {
        var result;
        myService.sendOutboundFiles2().then(function (res) {
            result = res;
        });
        $rootScope.$digest();
        expect(result).toBe('mockresult');
    }));
});

Which tests this very simple service function: 哪个测试这个非常简单的服务功能:

sendOutboundFiles2() {
     return fileSystemService.listFiles('Cached/Outbound').then(function(outfiles) {
         return outfiles;
     })
}

However when the test runs, it fails with a spurious Error: Unexpected request: GET blah\\blah\\blah.html No more request expected at $httpBackend error but i have no idea why as neither this test nor the service dependencies do anything with $httpBackend. 然而,当测试运行时,它失败并出现虚假Error: Unexpected request: GET blah\\blah\\blah.html No more request expected at $httpBackend错误但我不知道为什么因为这个测试和服务依赖项都没有做任何事情与$ httpBackend。

MORE INFO 更多信息

If i comment out my existing controller tests, I get this error: 如果我注释掉我现有的控制器测试,我会收到此错误: 仅限服务测试

If i add my controller tests back in, I get this error: 如果我重新添加我的控制器测试,我会收到此错误: 在此输入图像描述

So depending on which tests i add or remove, the HTML file in the GET error changes. 因此,根据我添加或删除的测试, GET错误中的HTML文件会发生变化。 But all the controller tests run fine. 但是所有的控制器测试运行良好。 WTF?!?!?!!??!?!!? WTF?!?!?!??!?!?

The problem is caused by Ionic's keen prefetching of all templates into a cache. 问题是由Ionic将所有模板强烈预取到缓存中引起的。 No idea why this doesn't occur when testing a controller though. 不知道为什么在测试控制器时不会发生这种情况。 The problem only appears when i was testing a service. 该问题仅在我测试服务时出现。 Any way, I found this thread: Karma test breaks after using ui-router and the relevant fix is to add this snippets before injecting any dependencies: 无论如何,我发现这个线程: 使用ui-router后Karma测试中断 ,相关修复是在注入任何依赖项之前添加此片段:

  beforeEach(module(function($provide) {
    $provide.value('$ionicTemplateCache', function(){} );
  }));

This stubs out the $ionicTemplateCache and prevents it from trying to preload all ui-router templates into the Ionic cache. 这会截断$ ionicTemplateCache,并阻止它尝试将所有ui-router模板预加载到Ionic缓存中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM