在组件成员测试中调用了如何测试操作



如何测试在组件中调用了操作?

有多种触发操作的方法,比如点击按钮。现在我想测试一下,当点击该按钮时调用的操作是否真的被调用了。类似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?
})

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

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

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

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

测试操作是否被调用的惯用方法是编写一个模拟函数并断言它将被调用。在您的示例中,在关闭操作之前,编写这种测试的方法如下:

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?
});

如今,使用闭包操作范式,绑定mock函数的正确方法将是

// 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)}}`)

最新更新