chaijs / chai-factories

Factories over fixtures. Chai Assertion Library.
23 stars 2 forks source link

Allow dynamic properties #26

Open dkniffin opened 6 years ago

dkniffin commented 6 years ago

The biggest reason to use factories instead of fixtures is that the properties are not static, so your tests aren't depending on static "magic" values. This article explains pretty well why thoughtbot's factory_girl gem is better than the built-in rails fixtures.

For this reason, I think this library should support generating dynamic properties.

For example:

chai.factory('person', { 
  age: () => { Math.floor(Math.random() * (100 - 5)) + 5) } // Pick a random age between 5 and 100.
});

var user1 = chai.create('person');
var user2 = chai.create('person');
console.log(user1.age); // Logs 31
console.log(user2.age); // Logs 57
dwoowb commented 6 years ago

Ran into this as well, this is the way I got your desired effect (I use FakerJS in my example):

const factoryData = () => ({
  id: faker.random.uuid()
});

chai.factory('myModel', {});

const myModelFactory = (opts) => (
  chai.create(
    'myModel',
    {
      ...factoryData(),
      ...opts
    }
  )
);

module.exports = myModelFactory;

Also, this way I keep my factory modularized for import wherever it's needed.