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

How do I test a computed property on a component in Ember?

我有一个组件 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);
});

为了测试计算的 属性,您需要编写一个 unit 测试。

单元测试不呈现 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