Ember.js 如何测试组件集成测试中是否触发了操作?

Ember.js 如何测试组件集成测试中是否触发了操作?,ember.js,Ember.js,我有一个非常简单的组件,我正在尝试测试,当按钮被点击时,相应的动作被触发。我尽可能地关注文档,也阅读了几篇博客文章以及涉及相同材料的问题,因此尝试了几种微妙的不同方法来实现这一点,但我就是无法通过测试。我已经确认它确实在浏览器中工作。我做错了什么 add-thing.hbs: {{#if displayForm}} <form class="form-inline">...form content...</form> {{else}} <button {{actio

我有一个非常简单的组件,我正在尝试测试,当按钮被点击时,相应的动作被触发。我尽可能地关注文档,也阅读了几篇博客文章以及涉及相同材料的问题,因此尝试了几种微妙的不同方法来实现这一点,但我就是无法通过测试。我已经确认它确实在浏览器中工作。我做错了什么

add-thing.hbs:

{{#if displayForm}}
<form class="form-inline">...form content...</form>
{{else}}
<button {{action 'toggleForm'}} class="btn btn-default add">Add</button>
{{/if}}
add-thing-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: |
...

余烬:v2.14.0

看起来你有两种不同的事情发生

this.toggleProperty('displayForm')

该操作将
displayForm
从true切换到false,但不会“冒泡”或在任何地方出现。单击按钮将启动它,然后就是它

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

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

看起来像

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

看起来您发生了两件不同的事情

this.toggleProperty('displayForm')

该操作将
displayForm
从true切换到false,但不会“冒泡”或在任何地方出现。单击按钮将启动它,然后就是它

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

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

看起来像

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

“注意这次toggleForm上没有引号,这意味着调用传入的操作”-这是一个有趣的区别,我没有从文档中捕捉到,谢谢。“注意这次toggleForm上没有引号,这意味着调用传入的操作”-这是一个有趣的区别,我没有从文档中捕捉到,谢谢。