如何在Ember中测试组件上的计算属性?

时间:2018-10-08 21:28:59

标签: ember.js integration-testing

我有一个组件foo-table,我正在传递一个称为myList的对象列表。我正在对列表进行排序的组件上设置一个计算属性。见下文:

// app/components/foo-table.js
export default Component.extend({
  sortedList: computed('myList', function foo() {
    const myList = this.getWithDefault('myList', []);
    return myList.sortBy('bar');
  }),
});

如何编写测试以确保对计算所得的属性进行排序?这是我到目前为止的内容:

// tests/integration/foo-table-test.js
const MY_LIST = ['foo', 'bar', 'baz']

test('it renders company industry component', function (assert) {
  this.set('myList', MY_LIST);

  this.render(hbs`
    {{foo-table myList=myList}}
  `);

  // TODO
  assert.equal(true, false);
});

1 个答案:

答案 0 :(得分:1)

为了测试计算所得的属性,您将需要编写单元测试。

单元测试不呈现DOM,但允许您直接访问被测模块。

// tests/unit/components/foo-table-test.js
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';

module('Unit | Component | foo-table', function(hooks) {
  setupTest(hooks);

  test('property: #sortedList', function(assert) {
    const component = this.owner.factoryFor('component:foo-table').create();

    const inputs = [
      { bar: 'beta' },
      { bar: 'gamma' },
      { bar: 'alpha' }
    ];

    component.set('myList', inputs);

    const expected = [
      { bar: 'alpha' },
      { bar: 'beta' },
      { bar: 'gamma' }
    ];

    assert.deepEqual(component.get('sortedList'), expected, 'list is sorted by bar');
  });
});

您可以像这样生成单元测试:ember generate component-test foo-table --unit

此答案是Ember 3.5的最新版本

相关问题