2017-03-13 68 views
0

我想为我的Angular 1.5组件基于这个tutorial编写一些单元测试。

import notificationBannerTemplate from 'app/components/notification-banner/notification-banner.html'; 

const notificationBanner = { 
    templateUrl: notificationBannerTemplate, 
    controller: notificationBannerController, 
    bindings: { 
     user: '<notificationBannerUser', 
     onNotificationClick: '<notificationBannerOnNotificationClick', 
    }, 
}; 

notificationBanner.$inject = ['$state']; 

function notificationBannerController($state) { 
    const ctrl = this; 

    ctrl.$onInit = function() { 
     ctrl.goToProfile = goToProfile; 
    }; 

    function goToProfile() { 
     ctrl.onNotificationClick(); 
     $state.go('app.profile.settings'); 
    } 
} 

export default notificationBanner; 

而且我的测试是这样的:

import unitHelpers from 'test/unit/unit-helpers.js'; 

describe('notificationBanner component',() => { 
    let parentScope; 
    let element; 
    let state; 

    const $stateMock = {}; 

    beforeEach(() => { 
     angular.mock.module(($provide) => { 
      $provide.value('$state', $stateMock); 
     }); 
    }); 
    beforeEach(angular.mock.module('CustomerComponentsModule')); 

    beforeEach(inject(($compile, $rootScope) => { 
     parentScope = $rootScope.$new(); 
     state = jasmine.createSpyObj('$state', ['go']); 


     parentScope.user = { 
      email: '[email protected]', 
     }; 

     parentScope.closeBanner = function() { 
     }; 


     element = angular.element(
      `<notification-banner 
       notification-banner-user="user" 
       notification-banner-on-notification-click="closeBanner"> 
      </notification-banner>`); 
     $compile(element)(parentScope); 
     parentScope.$digest(); 
    })); 


    it('should call the goToProfile function when the button is clicked',() => { 
     const componentElement = unitHelpers.findByTestId(element, 'bounced-email-banner--button'); 
     componentElement.click(); 
     expect(state.go).toHaveBeenCalledWith('app.profile.settings'); 
    }); 
}); 

我从我在网上看了尝试了一些不同的东西,但我每次运行我的测试时,我得到了错误TypeError: undefined is not a constructor (evaluating '$state.go('app.profile.settings')')

我该如何测试?

回答

1

找出问题---不得不向我的$ stateMock添加一个'go'方法。

const $stateMock = { 
    go: jasmine.createSpy('go'), 
}; 

然后,我能够与expect($stateMock.go).toHaveBeenCalledWith('app.profile.settings');

+1

测试是的,这是它是如何做一般。 '$ stateMock'应该是'let'或'var',因为模拟应该在beforeEach中刷新。 – estus