【问题标题】:Why isn't $injector finding $state in my unit test?为什么 $injector 在我的单元测试中没有找到 $state?
【发布时间】:2016-08-25 22:22:34
【问题描述】:

以下是我的模块和单元测试设置。当我尝试设置 $state 时,$injector.get("$state") 会抛出总是很有趣的 Unknown provider: $stateProvider 错误,我不明白为什么。

angular.module("my-module", [
        //Third Party
        "ui.bootstrap",
        "ui.router",
        "toaster",
        "angular-loading-bar",
        "ngAnimate",
        "ngSanitize",
        "ApplicationInsightsModule",
        "pascalprecht.translate"
]);

describe("something descriptive and helpful", (): void => {
    // a bunch of other service variables....
    var $state: any;

    // I've tried with and without this line
    beforeEach(() => angular.module("ui.router")); 

    beforeEach(() => {

        angular.module("my-module");

        inject(($injector: ng.auto.IInjectorService): void => {
            // a bunch of other service variable assignments
            $state = $injector.get("$state");
        });
});

【问题讨论】:

  • 还应该注意的是,在规范中使用真正的路由器是很尴尬的。尽可能坚持使用 $stateProvider/$state 模拟。
  • @estus 所以,如果我必须模拟我的整个路线配置......测试它有什么意义?那时我实际上正在重写代码,对吗?似乎不值得。

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


【解决方案1】:

你需要打电话

angular.mock.module("my-module")

加载模块。

【讨论】:

  • 我试过只做模拟并且 $state 解析,但是我的 ui-router 状态都不可用。例如,$state.go("home") 不起作用。
  • 没有足够的代码来理解为什么会发生这种情况,但是进入一个状态并不是你通常在单元测试中所做的。通常,您测试一个控制器,监视 $state.go() 服务,并验证(例如)在控制器成功提交表单后,它调用 $state.go() 以转到正确的状态。
  • 对不起,我想一点上下文会有所帮助。我想做的是对配置进行单元测试。所以,当我打电话给$state.go("home") 时,我可以检查$state.current.name 或检查url == "\home"。这超出了我的问题范围,所以我接受了你的回答。这只是我一直在努力解决的难题的一部分。
【解决方案2】:

模拟$stateProvider$state 的目的是存根第三方服务并仅单独测试您自己的代码,从而减少活动部件的数量。

基本上是

beforeEach(module("my-module", ($provide) => {
  $provide.factory('$state', ($q) => ({
    go: jasmine.createSpy().andCallFake(() => $q.resolve());
  }));
})); 

it('...', inject(($state, ...) => {
  ...
  expect($state.go).toHaveBeenCalledWith('stateName');
});

此时 ui.router 模块不应该加载到测试模块中,因为它需要额外的存根。

另请参阅this answer,了解如何测试$stateProvider 路由配置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    相关资源
    最近更新 更多