Git Product home page Git Product logo

autofixturejs's Introduction

Deprecated

I did a complete rewrite of this package and published it with a different name. Efate. It has the same basic api, but is modular and extensible, and easier to use.

autofixturejs Build Status Coverage Status Join the chat at https://gitter.im/autofixturejs/Lobby

AutoFixture is a test fixture library that allows users to define fixtures for testing and populates them with pseudo random data.

This library is inspired by Factory-Girl (and the similar node variations) and NBuilder.

Usages

Using the library consists of two parts, 1) defining the factories and 2) creating them in your tests

Creating a factory

You can define an object factory in one of the ways

  • Array of strings
  • object notation

Fields Defined with an Array

Factory.define('User',['first_name','last_name','email'])

This will create an object with the fields specified in the array

var user = Factory.create('User')

The user object will have the fields specified in the definition with pseudo random values:

{
    first_name: 'first_name1',
    last_name: 'last_name1',
    email: 'email1'
}

When you create another instance of this object with the factory, the numbers will be incremented:

    //second object:
    var user2 = factory.create('User')
    
    {
        first_name: 'first_name2',
        last_name: 'last_name2',
        email: 'email2'
    }

You can also create an array of fixtures, each with with unique values.

var users = factory.createListOf('User',2)

[
    {
        first_name: 'first_name1',
        last_name: 'last_name1',
        email: 'email1'
    },
    {
        first_name: 'first_name2',
        last_name: 'last_name2',
        email: 'email2'
    }

Name Generators

You can generate random names without the generic first_name1 values

var user = factory.create('User',[
  'firstName'.asFirstName(),
  'lastName'.asLastName(),
  'fullName'.asFullName()
]);

Will generate names randomly selected from a list. asFullName() will concatenate a first name and last name.

It currently selects from a list of 25 first and last names. If this is not enough let me know and I will increase the pool size

Overriding values

You can override the values at creation time, allowing you to create a generic fixture and change just the values you need for a specific test.

factory.define('User',[
    'first_name',
    'roles'.asArray(1)
]);

var adminUser = factory.create('User',{roles:['admin']});

Alternatively you can pass a function as the override which will give you more control over the result of the override. This is especially helpful for deeply nested objects.

var user = Factory.create('user', (user)=> {
			user.first_name = 'James';
			user.last_name = 'Kirk';
			user.orders[0] = 'new order';
			return user;
		})

You can append new fields through overrides as well. This is useful to create a fixture that could either be passed to an orm like Mongoose or bookshelf without and id. But if you want to simulated an already persisted fixture, you can an id attribute.

factory.define('User', ['first_name', 'last_name']);

// un-persisted fixture:
var user = factory.create('User'); // result: { first_name: 'first_name1', last_name: 'last_name1' }

// persisted user with an id field
var user = factory.create('User', { id: 1 }); // result: { first_name: 'first_name1', last_name: 'last_name1', id: 1 }

To change the behavior of the factory and return specific data types, several helper methods are added to the string object

Factory.define('User',[
    'first_name',
    'id'.asNumber(),
    'created'.asDate(),
    'roles'.asArray(2),
    'department'.asConstant('Sales'),
    'city'.withValue('MyCity'),
    'has_car'.asBoolean()
    'email'.asEmail(),
    'color'.pickFrom(['green', 'yellow', 'red'])
    ]);
    
//created will be DateTime.now
var user = Factory.create('user')
{
    first_name: 'first_name1',
    id: 1
    created: Date
    roles: ['roles1','roles2'],
    city: 'MyCity1'
}

asConstant will create the same value for all fixtures

Custom generators can be defined as well:

Factory.define('User',[
'first_name',
'email'.as(function(i){ return 'email'+i+'@email.com';});
]);

var user = factory.create('User');

{
    first_name: 'first_name1',
    email: '[email protected]'
}

You can also use other Factories to generate fields

Factory.define('User',[
    'first_name',
    
]);

Factory.define('Order',[
    'id'.asNumber(),
    'order_date'.asDate()
    'user'.fromFixture('User')
]);

Or a list of fixtures

//generates orders property as an array with five Order objects
Factory.define('user',[
  'name'.asFullName(),
  'orders'.asListOfFixtures('Order',5)
]);

Using Objects to Define a Factory

You can also use an object to define your fixtures. When you use an object the values for each field are used to create random data when you create the fixture

factory.define('User',{first_name, 'first', created_at: new Date(), id:1});
var user = factory.create('User');
{
    first_name: 'first1';
    created_at: new Date
    id: 1
}

Creating a Fixtures file

Generally speaking you'll want to put the fixture definitions into a single file and reuse for different tests.

There are several ways to do this, but what has worked best for me is to create a fixtures file, define the fixtures and export the factory.

Create a module that takes the factory as a function dependency

//fixtures.js
=============
var factory = require('autofixture');

factory.define ...

exports.module = factory;

In your test files just require your fixture and use the exported factor

//tests.js
var factory = require('./fixtures')

Now you can use the factory to access your defined fixtures.

describe("my tests",functio(){
    var user = factory.create('user');
    
});

Change Log: -- 1.0 -- Fixed issue with overriding array properties. -- Can now append new properties with overrides.

autofixturejs's People

Contributors

gitter-badger avatar hrkns avatar jcteague avatar kompiro avatar sprohaszka avatar vitaliy-urazov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

autofixturejs's Issues

Potential name confusion

Hi

Please accept my apologies if you consider this a misuse of a GitHub issue.

I came across this project today because I have a search agent set up to watch for the name AutoFixture, and just wanted to drop you a line... Please read on, this isn't a cease and desist letter - just a friendly note that the name may confuse some users...

The reason I have a search agent looking for the name AutoFixture is that I'm the inventor and Benevolent Dictator of a fairly successful open source project called AutoFixture.

Now, you are entirely free to use the name AutoFixture for a Javascript implementation - you probably arrived at the name the same way that I did. However, I just wanted to point you to the existing AutoFixture project, because it may be a potential source of confusion to users.

Obviously, node programmers are likely to be blissfully unaware of the .NET AutoFixture project, but people with prior experience with AutoFixture for .NET may be confused if autofixturejs uses completely different concepts, etc.

Additionally, it may make it difficult to search for AutoFixture documentation, etc. The reason I'm writing is that this has the potential to confuse both AutoFixture .NET users, as well as autofixturejs users.

Perhaps we could deal with such potential issues in one of the following ways:

  • Align the concepts and names etc. between the two projects. A couple of years ago, @moodmosaic expressed an interest in creating a port of AutoFixture to Javascript, and although I don't currently have the bandwidth to pour a lot of hours into this, I'd certainly be interested in using it myself. Perhaps we could even make autofixturejs part of the AutoFixture GitHub organisation.
  • Perhaps find another name for this Javascript project.

You are completely free to ignore this message, and keep working on your project. My motivation for writing to you is only that, based on the ReadMe for this project, it looks like you're unaware of the existing AutoFixture project, and I just wanted to point out to you that prior art exists, and that it may confuse your potential users.

Version 2.0 rewrite

This project has been around for a long time. When I first started it, it was pre ES6 and the internals is starting to show it's age it's time for a rewrite.

Fixture Definition

I think the fixture definition api has stood to the test in time and I don't forsee making any changes to how fixtures are defined, but export them seperately so you can import them directly into your tests.

const UserFixture = Factory.create('User', [
  'firstName',
  'lastName',
  'email'.asEmail(),
]);
module.exports = {
  UserFixture,
}

However, a plugin approach for builder functions might be interesting so you could create new types of builders could be interesting. It's not hard right now, just add a function following the pattern of existing builders. But you have to add it in all tests, or setup to use.

Factory.addBuilder('customValueBuilder', (fieldName, increment, {param1, param2}) => {
  return value_for_field
});
const UserFixture = Factory.define([
  'customValue'.customValueBuilder(1, 2),
]);

Fixture usage

Moving to module import approach to using a fixture, first suggested in this issue

const {UserFixture} = require('../fixtures')
const fixture1 = UserFixture.create();  //simplest use, all defaults
const fixture2 = UserFixture.create({
  firstName: 'firstName', //  simple overiding
  email: (incrementer) => `email${incrementer}@example.com` // new feature
});
// exists today, but a little clunky
const fixture = UserFixture.create((fixture)=>{
  fixture.firstName = 'firstName'
});

Any other suggestions?

I'm going to start work in this version this week

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.