如何测试动作在组件ember测试中被调用

时间:2015-11-08 04:04:14

标签: ember.js ember-cli ember-testing

如何测试组件中是否调用了某个操作?

触发动作有多种方法,例如点击按钮。现在我想测试实际调用单击该按钮时调用的操作。像expect.functionName.to.be.called或其他东西。

我有以下代码

test('it closes the create dialog when close btn is clicked', function(assert) {
  this.render(hbs`{{group-create cancelCreateAction="cancelAction"}}`)

  this.$('button.btn--primary').click()
  expect('myAction').to.be.called?
})

所以我只是想知道我能在那里做什么?

2 个答案:

答案 0 :(得分:1)

你的行动做了我们不知道的事情。但这是一个小测试,我写了检查一些DOM元素和当前路线。如果没有你告诉我们你的行为是什么,很难说。

click('.someSavingButton');

   andThen(function() {
     assert.equal(currentRouteName(), 'index');
     assert.equal(find('.something-new-in-the-dom').length, 1, "New item in HTML");

答案 1 :(得分:1)

我偶然发现了这个问题,同时也在寻找一种在集成测试中测试冒泡操作的方法(相反 关闭行动)。也许你已经找到了解决方案,但我会回答让下一个人比​​我更早找到它。

测试动作是否被调用的惯用方法是编写一个模拟函数并声明它将被调用。 在您的示例中 - 在关闭操作之前 - 编写此类测试的方法如下:

test('it closes the create dialog when close btn is clicked', function(assert) {
  // make sure our assertion is actually tested
  assert.expect(1);

  // bind the action in the current test
  this.on('cancelAction', (actual) => {
    let expected = { whatever: 'you have expected' };
    assert.deepEquals(actual, expected);

    // or maybe just an assert.ok(true) - but I am not sure if this is "good" style
  });

  this.render(hbs`{{group-create cancelCreateAction="cancelAction"}}`)

  this.$('button.btn--primary').click()
  expect('myAction').to.be.called?
});

如今,使用闭包动作范例,绑定模拟函数的正确方法是

// bind the action in the current test
this.set('cancelAction', (actual) => {
  let expected = { whatever: 'you have expected' };
  assert.deepEquals(actual, expected);
});

this.render(hbs`{{group-create cancelCreateAction=(action cancelAction)}}`)