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

prepare-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...
}


prepare-next-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.

07-24 09:50