2017-03-13 4 views
0

zu machen Ich versuche, einige Komponententests für meine Angular 1.5-Komponenten basierend auf dieser tutorial zu schreiben.

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; 

Und mein Test sieht wie folgt aus:

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'); 
    }); 
}); 

Ich habe ein paar verschiedene Dinge ausprobiert, was ich online gelesen habe, aber jedes Mal, wenn ich meinen Test laufen bekomme ich die Fehler TypeError: undefined is not a constructor (evaluating '$state.go('app.profile.settings')')

Wie kann ich das testen?

Antwort

1

Ermittelt das Problem --- hatte eine 'go' Methode zu meinem $ stateMock hinzufügen.

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

Dann konnte ich mit expect($stateMock.go).toHaveBeenCalledWith('app.profile.settings');

+1

Ja testen, das ist, wie es in der Regel geschieht. '$ stateMock' sollte' let' oder 'var' sein, da ein Mock in beforeEach aufgefrischt werden soll. – estus

Verwandte Themen