In Ember js, how to create or mock hasMany relationship in unit test

梦想与她 提交于 2019-12-09 21:41:49

问题


I'm unit-testing a model which has properties with DS.hasMany() relationships. Whenever I do the following unit-test, I keep getting this error in my test-runner: Error: Assertion Failed: All elements of a hasMany relationship must be instances of DS.Model, you passed [<Ember.Object:ember367>,<Ember.Object:ember368>]

Can someone shed some light into this, please?

Model:

export default DS.Model.extend({
  accounts: DS.hasMany('account'),
  servicesAccounts: DS.hasMany('services-account'),
  address: MF.fragment('address'),
  appEligibilities: MF.fragmentArray('app-eligibility'),

  appsForPremise: Ember.computed('accounts', function () {
    return DS.PromiseArray.create({
      promise: this.get('store').find('app', {
        account: this.get('accounts').mapBy('id')
      })
    });
  })
});

Model uni-test:

import { moduleForModel, test } from 'ember-qunit';
import Ember from 'ember';

moduleForModel('premise', 'Unit | Model | premise', {
  needs: [
    'model:account',
    'model:services-account',
    'model:address',
    'model:app-eligibility'
  ]
});

test('Apps for premise', function (assert) {
  let model = this.subject({
      accounts: [Ember.Object.create({
        id: 'account-1'
      }),
      Ember.Object.create({
        id: 'account-2'
      })],
      appsForPremise: sinon.spy()
    });

  Ember.run(() => {
  });

  assert.equal(model.get('appsForPremise'), '[{id: account-1}, {id: account-2}]');

});

回答1:


You cant pass regular ember objects to the hasMany relationship, they have to be store model objects. You can create them using the store, i.e.

 const store = this.store();
 Ember.run(() => {
    const model = this.subject({
        accounts: [
          store.createRecord('services-account', {
            id: 'account-1'
        }),
          store.createRecord('services-account',{
            id: 'account-2'
        })],
        appsForPremise: sinon.spy()
    });
 });

Calls to the store methods have to go into the run loop, otherwise Ember will complain.



来源:https://stackoverflow.com/questions/38517927/in-ember-js-how-to-create-or-mock-hasmany-relationship-in-unit-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!