用于单元测试的 EmberJS 服务注入 (Ember QUnit) [英] EmberJS Service Injection for Unit Tests (Ember QUnit)

查看:16
本文介绍了用于单元测试的 EmberJS 服务注入 (Ember QUnit)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

规格:

  • Ember 版本:1.13.8
  • 节点:0.10.33
  • npm:2.13.4

我有

import Alias from "../../../services/alias";
....

moduleFor("controller:test", "Controller: test", {
  integration: true,

  beforeEach: function() {
    this.register('service:alias', Alias, {singleton: true});
    this.inject.service('alias', { as: 'alias' });
    this.advanceReadiness();
  },
});
...

test('Alias Alias Alias ', function(assert) {
  var controller = this.subject();

  //sample function
  controller.send("test");
  assert.equal(true, controller.alias.get("alias"), "alias should be true");
});

(以别名"为例,因为我不允许显示实际代码)

(Using 'alias' as example because I'm not allow to show actual code)

我尝试初始化服务,但在 Ember Qunit 测试期间,控制器没有注入服务.

I've tried to initialize the service but during Ember Qunit tests, controllers do not have the services injected to them.

我尝试将注入放入:init() 而不是 beforeEach,也不起作用...

I've tried putting the injection in: init() instead of beforeEach, doesn't work either...

如何在单元测试期间注入它?

How do I inject it during unit tests?

我在调试器中放置了断点以查看我的控制器是否有服务,但在测试期间没有.但是,在正常的 ember 服务中没问题.

I put break points in the debugger to see if my controllers have the service, it doesn't during tests. It's fine on normal ember serve, however.

推荐答案

您不必导入服务.您必须在如下需求中包含服务.

You don't have to import service. You have to include service in needs like below.

moduleFor("controller:test", {
   needs: ['service:alias']
});

例如:

服务/别名.js

Em.service.extend({
  name: 'john'
});

控制器/test.js

controllers / test.js

Em.Controller.extend({
  alias: Em.service.inject(),

  test: function() {
    alert(this.get('alias.name');
    }
  });

tests/unit/controllers/test-test.js

tests/unit/controllers/test-test.js

moduleFor('controller:test', {
  needs: ['service:store']
});

test('Alias Alias Alias', function(assert) {

    var controller = this.subject();
    assert.equal(controller.get('store.name'), 'john);

    });

为了运行这个测试,Ember 将生成一个带有 controller testservice alias 的容器.因此,您可以访问带有名称前缀的服务属性.

For this test to run, Ember will generate a container with the controller test and service alias. So you can access the service properties with its name prefixed.

这篇关于用于单元测试的 EmberJS 服务注入 (Ember QUnit)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆