单元测试余烬并发任务和收益 [英] Unit testing ember-concurrency tasks and yields

查看:84
本文介绍了单元测试余烬并发任务和收益的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的项目中有很多代码由于余烬并发任务而没有涉及。

We have a lot of code in our project that isn't covered because of ember concurrency tasks.

是否有一种简单的方法来对包含以下内容的控制器进行单元测试类似于以下内容:

Is there a straightforward way of unit testing an controller that contains something like the following:

export default Controller.extend({
    updateProject: task(function* () {
        this.model.project.set('title', this.newTitle);
        try {
            yield this.model.project.save();
            this.growl.success('success');
        } catch (error) {
            this.growl.alert(error.message);
        }
    })
});```


推荐答案

您可以通过以下方式对任务进行单元测试:调用 someTask.perform()。对于给定的任务,您可以存根您需要进行全面测试的内容:

You can unit test a task like that by calling someTask.perform(). For the given task you can stub what you need to in order to test it thoroughly:

test('update project task sets the project title and calls save', function(assert) {

  const model = {
    project: {
      set: this.spy(),
      save: this.spy()
    }
  };
  const growl = {
    success: this.spy()
  };

  // using new syntax
  const controller = this.owner.factoryFor('controller:someController').create({ model, growl, newTitle: 'someTitle' });

  controller.updateProject.perform();

  assert.ok(model.project.set.calledWith('someTitle'), 'set project title');
  assert.ok(growl.success.calledWith('success'), 'called growl.success()');
});

这是使用 sinon ember-sinon -qunit 从测试上下文访问sinon,但是这些对于单元测试不是必需的。您可以使用断言而不是间谍来对模型和服务等进行存根:

This is using spies from sinon and ember-sinon-qunit to access sinon from a test context, but these are not necessary for unit testing. You could stub the model and services, etc. with assertions instead of spies:

const model = {
  project: {
    set: (title) => {
      assert.equal(title, 'someTitle', 'set project title');
    },
    save: () => {
      assert.ok(1, 'saved project');
    }
  }
};

要测试可以从存根模型中抛出的渔获量.project.save()方法:

To test the catch you can throw from your stubbed model.project.save() method:

const model = {
  project: {
    ...
    save: () => throw new Error("go to catch!")
  }
};

这篇关于单元测试余烬并发任务和收益的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆