如何测试在组件集成测试中触发的操作?

时间:2017-08-31 02:11:05

标签: ember.js

我有一个非常简单的组件,我正在尝试测试它,当单击该按钮时,会触发相应的操作。我尽可能地密切关注文档,并阅读了几篇博文和涉及相同材料的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

1 个答案:

答案 0 :(得分:2)

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

this.toggleProperty('displayForm')

该操作会将displayForm从true切换为false,但它不会“冒泡”或在任何地方上升。单击该按钮将触发它,然后就是它。

另一方面,您的测试正在查看是否单击该按钮会将向上的操作发送到另一个级别。

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

可能看起来像

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

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