如何测试在组件集成测试中触发了一个动作?

How to test that an action is fired in a component integration test?

我有一个非常简单的组件,我正在尝试测试它,当单击按钮时,会触发适当的操作。我尽可能地关注了文档,还阅读了几篇博客文章和涵盖相同 material 的 SO 问题,因此尝试了几种微妙的不同方法来使它起作用,但我就是无法进行测试经过。我已经确认它确实在浏览器中有效。我做错了什么?

添加-thing.hbs:

{{#if displayForm}}
<form class="form-inline">...form content...</form>
{{else}}
<button {{action 'toggleForm'}} class="btn btn-default add">Add</button>
{{/if}}

添加-thing.js:

import Ember from 'ember'

export default Ember.Component.extend({
  displayForm: false,

  actions: {
     toggleForm () {
       this.toggleProperty('displayForm')
    }
  }
})

添加-test.js:

import Ember from 'ember'
import { moduleForComponent, test } from 'ember-qunit'
import hbs from 'htmlbars-inline-precompile'

moduleForComponent('add-group', 'Integration | Component | add thing', {
  integration: true
})
test('it toggles the form when the Add button is clicked', function (assert) {
  assert.expect(1)
  this.set('assertCalled', () => { assert.ok(true) })
  // Have also tried this.on here instead of this.set

  this.render(hbs`{{add-thing toggleForm=(action assertCalled)}}`)
  // Have also tried passing in the action like {{add-thing toggleForm='assertCalled'}} as some blog posts suggest
  Ember.run(() => document.querySelector('button.add').click())
  // Have also tried just a this.$('button.add').click() here
})

测试输出:

not ok 16 PhantomJS 2.1 - Integration | Component | add thing: it toggles the form when the Add button is clicked
---
    actual: >
        null
    expected: >
        null
    stack: >
        http://localhost:7357/assets/tests.js:221:24
        exports@http://localhost:7357/assets/vendor.js:111:37
        requireModule@http://localhost:7357/assets/vendor.js:32:25
        require@http://localhost:7357/assets/test-support.js:20229:14
        loadModules@http://localhost:7357/assets/test-support.js:20221:21
        load@http://localhost:7357/assets/test-support.js:20251:33
        http://localhost:7357/assets/test-support.js:7708:22
    message: >
        Expected 1 assertions, but 0 were run
    Log: |
...

Ember:v2.14.0

您似乎发生了两件不同的事情。

this.toggleProperty('displayForm')

该操作会将 displayForm 从 true 切换为 false,但不会 "bubble up" 或上升到任何位置。单击按钮将触发它,然后就可以了。

另一方面,您的测试是查看单击按钮是否会触发 up 到另一个级别的操作。

您可以通过在单击按钮 assert.equal(this.$('form').length, 1); 后检查表单是否存在来对此进行测试。或者您可以更改组件的工作方式,但除非您想要 操作冒泡,否则您不需要走那条路。

可能看起来像

toggleForm () {
  this.sendAction('toggleForm');
}

<button {{action toggleForm}}">Add</button> (注意这次 `toggle 表单上没有引号,这意味着调用传入的操作。)