2017-07-06 179 views
0

這是試圖運行我的單元測試時,我看到的錯誤在組件控制器提供的服務多數民衆贊成..嘲弄在單元測試

Expected undefined to be defined. 
TypeError: undefined is not an object (evaluating '$rootScope.$digest') 

Module 'ThirdPartyModule' 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. 

任何想法如何嘲笑testService,使我仍然可以編譯我的組件?

test.component.spec.ts

import { TestModule } from '../index'; 

describe('Component: testComponent',() => { 

    let $rootScope: angular.IScope; 
    let element: angular.IAugmentedJQuery; 

    beforeEach(() => { 
    angular.mock.module('ui.router'); 
    angular.mock.module(TestModule.name); 
    }); 

    beforeEach(inject((
    _$rootScope_: angular.IScope, 
    $compile: angular.ICompileService, 
    _$state_: angular.ui.IStateService) => { 
    $rootScope = _$rootScope_; 
    element = angular.element('<test></test>'); 
    element = $compile(element)($rootScope); 
    })); 

    it('should verify component compiled and rendered template',() => { 
    expect(element).toBeDefined(); 
    $rootScope.$digest(); 
    let link = element.find('a'); 
    expect(link.text()).toContain('Click this link!'); 
    }); 
}); 

test.module.ts

import { TestComponent } from './test'; 

export let TestModule: ng.IModule = angular.module(
    'test', // my module name 
    ['ui.router', 'ThirdPartyModule']) // dependencies, ThirdPartyModule contains testService 
    .component('test', new TestComponent()); 

test.component.ts

import { TestComponentController } from './test.component.controller'; 

export class TestComponent implements ng.IComponentOptions { 
    public template: string = '<a ng-if="ctrl.serviceReturned">Click this link!</a>'; 
    public controller: Function = TestComponentController; 
    public controllerAs: string = 'ctrl'; 

    constructor() {} 
} 

test.component.controller.ts

export class TestComponentController { 

    public serviceReturned: boolean = false; 

    constructor(private testService: any) { 
    if (this.testService.isDone()) { 
     this.serviceReturned = true; 
    } 
    } 
} 

TestComponentController.$inject = ['testService']; 
+1

在注入過程中發生錯誤,導致$ rootScope和元素未定義,並且在此處未顯示。如果不知道錯誤,不可能說出什麼問題。如果它被壓制了,那就試試吧......在beforeEach之前。 – estus

+0

繼承人錯誤,我更新了問題..'模塊'ThirdPartyModule'不可用!您拼錯了模塊名稱或忘記加載模塊名稱。如果註冊一個模塊,確保你指定依賴關係作爲第二個參數。' – bobbyrne01

+0

我想這個錯誤解釋了這一切。該模塊未加載。 – estus

回答

0

您是否需要在angular.mock.module中添加'ThirdPartyModule'?