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

Tyl*_*cks 1 integration-testing ember.js

我有一个组件,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');
  }),
});
Run Code Online (Sandbox Code Playgroud)

如何编写测试以确保计算属性已排序?这是我到目前为止:

// 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);
});
Run Code Online (Sandbox Code Playgroud)

Gau*_*rav 5

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

单元测试不呈现 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');
  });
});
Run Code Online (Sandbox Code Playgroud)

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

此答案适用于 Ember 3.5