Ember单元测试具有冒泡动作的组件

Ember Unit Testing Components with bubble up action

本文关键字:组件 单元测试 Ember      更新时间:2023-09-26

我正试图编写一个单元测试,以确保在关闭模态时关闭属性。然而,我似乎在行动处理方面遇到了问题。我不断收到错误消息:
Error: <q12-reports@component:add-team-modal::ember294> had no action handler for: hideModal

这是modal.js组件:

stopSearch: function(modal) {
  modal.send('hideModal');
  this.setProperties({
    searchTerm: ''
  });
},
actions: {
  modalCancelled: function(modal) {
    this.stopSearch(modal);
  },
  etc...
}

正如你所看到的,我正在酝酿hideModal的行动。这是我试图写的单元测试:

test('closing modal clears properties correctly', function(assert) {
  assert.expect(2);
  let component = this.subject();   
  let firstSearchTerm;
  Ember.run(function() {
    component.set('searchTerm', 'test');
    firstSearchTerm = component.get('searchTerm');
    assert.ok(firstSearchTerm, 'test', 'set term properly');
    component.send('modalClosed', component);
  });
  assert.ok(firstSearchTerm, '', 'clears term properly');
})

在人们提到这一点之前,我已经在下面尝试过了。

test('closing modal clears properties correctly', function(assert) {
  assert.expect(2);
  let component = this.subject();   
  let firstSearchTerm;
  let $component = this.append();
  let targetObject = {
    externalHideModal: function() {
      assert.ok(true, 'hide modal was called.');
      return true;
    }
  }
  component.set('hideModal', 'externalHideModal');
  component.set('targetObject', targetObject);
  Ember.run(function() {
    component.set('searchTerm', 'test');
    firstSearchTerm = component.get('searchTerm');
    component.send('modalCancelled', component);
  });
  assert.ok(firstSearchTerm, '', 'clears term properly');
})

集成测试尝试(不起作用)。最后一个断言仍然读作"test"。

test('Closing modal clears properties of modal', function(assert) {
   assert.expect(1);
   this.render(hbs`{{modal}}`);
   //open modal
   this.$('.search').click();
   this.setProperties({
     searchTerm: 'test'
   });
   this.set('searchTerm', 'test');
   assert.equal(this.get('searchTerm'), 'test', 'sets properly');
   // cancel out of modal
   this.$('.modal-footer button').eq(1).click();
   let searchTerm = this.get('searchTerm');
   assert.equal(searchTerm, '', 'clears results properly');
});

如果您想断言您的组件发送了一个事件,您可以在集成测试上下文中添加一个事件侦听器。这还应该阻止引发未处理的事件错误。

assert.expect(2);
...
this.on('hideModal', function() {
  assert.ok(true, 'hide modal event fired');
});

这对于ember单元测试来说有点困难,所以我建议在测试组件UI交互时使用集成测试。