在 qunit 测试中模拟控制器。

Mocking controllerFor in qunit tests.

我有一个 mixin 可以帮助我完成一系列步骤。基本上它会查看当前步骤是什么,然后基于此执行一些魔术。问题是函数的第一行获取 this.controllerFor('document') 并且我不明白如何模拟 controllerFor 调用。我知道我可以,例如,将 {testing: "123"} 传递到测试中的 .create 中。这将给我 this.get('testing') 但我如何模拟 controllerFor?另外,需要明确的是,调用 controllerFor 的唯一原因是我可以获得 currentStep

准备-next.js

setNext: function() {
    let currentStep = this.controllerFor('document').get('currentStep');

    if (currentStep === 'First_step') {
        //do something
    } else {
        //do something else...
    }
    // Bunch more stuff happens...
}

准备下一步-test.js

import Ember from 'ember';
import PrepareNext from 'my-app/mixins/prepare-next';
import { module, test } from 'qunit';

module('mixin:prepare-next');

const PrepareNextObject = Ember.Object.extend(PrepareNext);
let subject;


test('#setNext does all the things', function(assert) {
  subject = PrepareNextObject.create();
  subject.setNext();
  //assert.equal(foo, bar);
});

您可以在测试前或测试中替换 controllerFor 方法:

import Ember from 'ember';
import PrepareNext from '../../../mixins/prepare-next';
import { module, test } from 'qunit';

module('mixin:prepare-next');

const PrepareNextObject = Ember.Object.extend(PrepareNext);

let subject;

test('#setNext does all the things', function(assert) {
  assert.expect(2);

  subject = PrepareNextObject.create();
  subject.controllerFor = () => {
    assert.ok(true, 'controllerFor called');
    return {
      get() {
        assert.ok(true, 'Get called');
        return 'First_step';
      }
    }
  };
  subject.setNext();
  //assert.equal(foo, bar);
});

Working demo.