简体   繁体   中英

create factory girl instance inside of creating another factory girl instance

This is what my data looks like in the database:

{
    "id": 4,
    "name": "New Sad",
    "open": true,
    "description": "The happiest place on earth!",
    "gps": "133.232, 121.021",
    "regionId": 1,
    "location": "{\"regionName\":\"Bishop\",\"regionId\":1}",
    "updatedAt": "2017-12-06T05:24:44.683Z",
    "createdAt": "2017-12-06T05:24:44.683Z"
}

I hava jsonb column, this is for searching reason because query all parent tables on the fly is too slow, which is why I am not using factory.assoc . I cannot use assoc and reference what it creates right away.

To define my factory-girl, I thought I could just do this:

module.exports = async factory => {
  const region = await factory.create('region');
  const area = factory.define('area', Area, () => {
    return {
      name: factory.chance('first'),
      open: true,
      description: factory.chance('sentence', {words: 5}),
      gps: '122.123, 123.342',
      regionId: factory.assoc('region', 'id'),
      location: JSON.stringify({
        regionName: region.dataValues.name,
        regionId: region.dataValues.id,
      }),
    };
  });
  return area;
};

Error message:

(node:49078) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Invalid factory 'region requested (node:49078) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Not sure why it didn't work the first time I tried it, but it works like this now:

const Area = require('../../src/models').Area;

module.exports = factory => {
  const area = factory.define('area', Area, async () => {
    const region = await factory.create('region');
    return {
      name: factory.chance('first'),
      open: true,
      description: factory.chance('sentence', {words: 5}),
      gps: '122.123, 123.342',
      regionId: region.dataValues.id,
      location: JSON.stringify({
        regionName: region.dataValues.name,
        regionId: region.dataValues.id,
      }),
    };
  });
  return area;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM