尝试使用$ state对控制器进行单元测试

时间:2017-03-13 15:30:49

标签: angularjs unit-testing

我正在尝试根据此tutorial为我的Angular 1.5组件编写一些单元测试。

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: 'test@test.com',
        };

        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 个答案:

答案 0 :(得分:1)

想出问题---必须在我的$ stateMock中添加一个'go'方法。

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

然后我可以使用expect($stateMock.go).toHaveBeenCalledWith('app.profile.settings');

进行测试