1

我有一个侧边栏组件,它依赖于通过初始化程序注入的侧边栏服务。

然后组件有一个计算的属性标题,它与服务上的相同属性相关联:

title: function () {
  return this.get('sideBarService.title');
}.property('sideBarService.title'),

这适用于应用程序本身,但是当服务更新时,我无法在集成测试中更新组件。

这是我的非工作集成测试:

import Ember from 'ember';
import startApp from '../helpers/start-app';
import hbs from 'htmlbars-inline-precompile';
import { moduleForComponent, test } from 'ember-qunit';

var application, container, sideBarService;

moduleForComponent('side-bar', 'Integration | side-bar',{
  integration: true,
  beforeEach: function() {
    application = startApp();
    container = application.__container__;
    sideBarService = container.lookup('service:side-bar');
  },

  afterEach: function() {
    Ember.run(application, 'destroy');
  }
});

test('it displays the correct title', function(assert) {
  assert.expect(1);

  Ember.run(function () {
    sideBarService.set('title', 'Hello');
  });

  this.render(hbs`
    {{side-bar}}
  `);

  var content = this.$('.side-bar-content .title').text().trim();
  var serviceTitle = sideBarService.get('title');
  // fails     
  assert.deepEqual(content, serviceTitle);
});

有趣的是,如果我在测试中调试并使用控制台抓取组件,然后从组件中抓取 sideBarService,它会知道更新的标题值,甚至组件本身的值标题似乎也已更新,但 dom 永远不会得到更新:

//debugged in browser console
var sb = container.lookup('component:side-bar')
undefined

sb.get('title')
"Hello"

sb.get('sideBarService.title')
"Hello"

this.$('.title').text().trim()
""

这是一个运行循环问题吗?如果是这样,我需要做什么才能将其关闭?

编辑:关于托兰的评论。这看起来对吗?

  var done = assert.async();
  var content = this.$('.side-bar-content .title').text().trim();
  var serviceTitle = sideBarService.get('title');
  setTimeout(function() {
    assert.deepEqual(content, serviceTitle);
    done();
  });
4

1 回答 1

1

我可能会通过避免在初始化程序中注入并使用Ember.inject.service帮助程序来解决这个问题。

// component

import Ember from 'ember'

const { Component, inject, computed } = Ember;
const { service } = inject;
const { alias } = computed;

export default Component.extend({

  sideBarService: service('side-bar'),

  title: alias('sideBarService.title')

});

然后在您的测试中,您可以在使用该组件时通过该服务。

import Ember from 'ember';
import startApp from '../helpers/start-app';
import hbs from 'htmlbars-inline-precompile';
import { moduleForComponent, test } from 'ember-qunit';

var application, container, sideBarService;

moduleForComponent('side-bar', 'Integration | side-bar',{
  integration: true,
  beforeEach: function() {
    application = startApp();
  },

  afterEach: function() {
    Ember.run(application, 'destroy');
  }
});

test('it displays the correct title', function(assert) {
  assert.expect(1);

  this.set('sideBarService', Ember.Object.create({
    title: 'hello'
  }));

  this.render(hbs`
    {{side-bar sideBarService=sideBarService}}
  `);

  var title = this.$('.side-bar-content .title').text().trim();
  assert.equal(title, 'hello'); // Hopefully passes
});
于 2015-09-21T18:58:08.830 回答