Search code examples
unit-testingember.jsember-data

Object mock using data factory guy addon


I am new to Embebr js and using ember-data-factory addon to mock ajax response however having trouble mocking below response.

 {
      "employee/profile": {
        "id": 60799,
        "gender": "Male",
        "fname": "Mick",
        "lname": "Hussey",
        "addresses": [
          "50345"      
        ]   
      },
      "employee/addresses": [
        {
          "id": "50345",
          "addressState": "GA",
          "zip": "30004"  
        }     
      ] 

    } 

To achieve this i have created both profile and address model in tests/factories/ directory. employee/profile Model

import FactoryGuy from 'ember-data-factory-guy';

FactoryGuy.define('employee/profile', {
  default: {    
    id: 60799,
    gender: 'Male',
    fname: 'Mick',
    lname: 'Hussey',
    addresses:  FactoryGuy.hasMany('employee/address')  
  } 
});

Address Model:

import FactoryGuy from 'ember-data-factory-guy';

FactoryGuy.define('employee/address', {
  default: {   
    id: '50345',
    addressState: 'GA',
    zip: '300014'   
    employee: FactoryGuy.belongsTo('employee/profile'),

  }
});

And when i try to build profile object using below code snippet, all the fields except addresses is getting populated.

let profile = this.build('employee/profile');

can anybody please help me understand whats going wrong.

Thanks Gautam


Solution

  • You need to define the relationship as follows:

    addresses:  FactoryGuy.hasMany('employee/address', 1)
    

    This way you indicate that you want an array of addresses with just one item in it. If you omit the last one, you will end up with an empty list of addresses. Please see the source code of hasMany in github.

    By the way, I have prepared you a twiddle in case you need it. I am not an expert; but I did my best. You can check factory definitions and unit test for profile model under unit/models/emoloyee/profile-test.js. Hope this helps.