【问题标题】:Testing angular sub-module can't find dependency测试角度子模块找不到依赖项
【发布时间】:2017-05-13 13:33:10
【问题描述】:

我正在尝试测试我的 angular 1(使用 typescript)模块,但我遇到了依赖项问题:

这些是我的模块:

app.module.ts

export const appModule: IModule = angular.module('app', [
    'ui.router',
    'ngMaterial',
    'ngMessages',
    'ngAnimate',
    'angularMoment',
    'ngMap',
    sharedModule.name,
    componentsModule.name
]);

shared.module.ts

export const sharedModule: IModule = angular.module('app.shared', [
    'ui.router',
    'ngMaterial',
    'ngMessages',
    'ngAnimate',
    'angularMoment',
    'ngMap'
]);

但在测试时,我在 all 的测试中遇到错误,但我的项目在浏览器中运行良好。所以只有测试找不到这样的依赖抛出错误:

Uncaught Error: [$injector:modulerr] Failed to instantiate module app.shared due to:
Error: [$injector:modulerr] Failed to instantiate module ui.router due to:
Error: [$injector:nomod] Module 'ui.router' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

但是当我将共享模块设置为:

export const sharedModule: IModule = angular.module('app.shared', []);

那么它在使用外部服务的测试中出错,例如:

Error: [$injector:unpr] Unknown provider: $stateProvider <- $state

测试如下:

describe('component: bookmark', () => {
    let parentScope: any;
    let element: any;

    beforeEach(angular.mock.module(sharedModule.name));

    beforeEach(inject(($compile: ng.ICompileService, $rootScope: ng.IRootScopeService) => {
        parentScope = $rootScope.$new();

        element = angular.element(`<bookmark></bookmark>`);
        $compile(element)(parentScope);

        parentScope.$digest();
    }));
    it('should display a star', () => {
        const someAttrValue: string = findIn(element, 'md-icon').text();
        console.debug('found ', someAttrValue);
        expect(someAttrValue).toEqual('star');

    });
});

而我的bookmark 需要$state

任何线索我可能做错了什么?

【问题讨论】:

    标签: angularjs unit-testing testing angularjs-components


    【解决方案1】:

    问题是我没有导入所有依赖项,

    错误依旧,所以当我导入ui-router时,它仍然说缺少ui-router,而缺少angular-material

    【讨论】: