【问题标题】:Unit testing ember-concurrency tasks and yields单元测试 ember 并发任务和产量
【发布时间】:2019-10-18 13:49:59
【问题描述】:

我们的项目中有很多代码由于 ember 并发任务而未被涵盖。

是否有一种直接的方法对包含以下内容的控制器进行单元测试:

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

【问题讨论】:

    标签: javascript unit-testing ember.js ember-testing ember-concurrency


    【解决方案1】:

    您可以通过调用someTask.perform() 对这样的任务进行单元测试。对于给定的任务,你可以存根你需要的东西以便彻底测试它:

    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()');
    });
    

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

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

    要测试你可以从你的存根 model.project.save() 方法中抛出的捕获:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-18
      • 2019-06-21
      • 1970-01-01
      • 2016-02-11
      • 1970-01-01
      • 1970-01-01
      • 2019-08-02
      • 1970-01-01
      相关资源
      最近更新 更多