测试setupController或私有Route方法时如何模拟模型

时间:2018-10-12 18:40:50

标签: unit-testing testing ember.js ember-data

当我在路由(单元)测试中尝试通过编写model来模拟let mockModel = this.owner.lookup('model:realModel');时,收到错误 Error: You should not call 'create' on a model. Instead, call 'store.createRecord' with the attributes you would like to set.

模拟model以测试setupController和其他私有路由方法中的处理的正确方法是什么?

用于说明测试setupController /专用路由方法的代码:

app \ routes \ application.js

export default Route.extend({

  _postModelProcessing(inputModel){
      ....
      return processedModelData;
  },

  setupController(controller, model){

  let processedModelData = _postModelProcessing(model);   

  }

})

tests \ unit \ routes \ application-test.js

module('Unit | Route | application', function(hooks) {
  setupTest(hooks);
  ...      
  test('private _postModelProcessing correctly processes model data', function(assert) {
    let route = this.owner.lookup('route:application');

    // This line throws the Error mentioned above
    let mockModel = this.owner.lookup('model:realModel');

  // what I hoped to do, if the above line didn't throw an error:
  let mockModelData = [
    mockModel.create({
      category: 'Leopard',
      childCategories: [],
      parentCategory: null
    }),
    mockModel.create({
      category: 'Snow Leopard',
      childCategories: [], 
      parentCategory: 'Leopard'
    }),
    mockModel.create({
      category: 'Persian Leopard',
      childCategories: [],
      parentCategory: 'Leopard'
    })
  ]

  let processedData = route._postModelProcessing(mockModelData);
  let leopardFirstChild = processedData[0].get('childCategories')[0];

  assert.equal(leopardFirstChild.get('category'), 'Snow Leopard');

  })

});

1 个答案:

答案 0 :(得分:0)

只要出现错误消息,请使用store.createRecord

module('Unit | Route | application', function(hooks) {
  setupTest(hooks);
  ...      
  test('private _postModelProcessing correctly processes model data', function(assert) {
    let route = this.owner.lookup('route:application');
    let store = this.owner.lookup('service:store');

  // what I hoped to do, if the above line didn't throw an error:
  let mockModelData = [
    store.createRecord('real-model', {
      category: 'Leopard',
      childCategories: [],
      parentCategory: null
    }),
    store.createRecord('real-model', {
      category: 'Snow Leopard',
      childCategories: [], 
      parentCategory: 'Leopard'
    }),
    store.createRecord('real-model', {
      category: 'Persian Leopard',
      childCategories: [],
      parentCategory: 'Leopard'
    })
  ]

  let processedData = route._postModelProcessing(mockModelData);
  let leopardFirstChild = processedData[0].get('childCategories')[0];

  assert.equal(leopardFirstChild.get('category'), 'Snow Leopard');

  })

});