将模拟$状态注入角度单元测试

时间:2016-04-14 23:05:42

标签: javascript angularjs unit-testing angular-ui-router

我是Angular单元测试中的一个相对弱者,我正在努力引导我作为一个简单的单元测试。

我的班级

class CampaignController {
    constructor($state) {
        this.$state = $state;
    }

    submit() {
        this.$state.transitionTo('some.state');
    }
}
export { CampaignController };

我的测试

import { expect } from 'chai';
import angular from 'angular';
import { CampaignController } from './campaign.controller';

let component;

describe('campaign-controller', function() {

    var $state;

    beforeEach(inject(function (_$state_) {
        $state = _$state_;
        component = new CampaignController($state);
    }));


    it('should update state on submit', () => {
        component.submit();
        expect($state.current.name).to.be('some.state');
    });
});

我最终收到此错误

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

我在这里缺少什么?

1 个答案:

答案 0 :(得分:2)

您没有在beforeEach中加载任何模块,因此angular-ui路由器不可用。至少,您需要加载ui.router模块。

例如,您可能在您的之前有一个单独的beforeEach块:

beforeEach(module('ui.router'));

beforeEach(inject(function (_$state_) {
    $state = _$state_;
    component = new CampaignController($state);
}));