0
votes

I have a page that has multiple AJAX Calls to the server. Now, I am mocking the data with Mirage for testing purpose. For that, I am using Factories.

I have factories for all the models being used during the page render. All the models have many relationships, few models have hasMany and belongsTo, the other models have hasMany alone.

I came across in the net to use aftercreate hook for these kind of associations.

My doubt is :

Model author.js in mirage has :

author: hasMany('post'),
afterCreate(a, server) {
   server.create('b', {a});
}

Similarly, Model post.js in mirage has :

author: belongsTo(),
aftercreate(b, server) {
   server.create('a', {post});
}

My doubt is, won't it be a recursive calls, after each afterCreate hook, the other model is getting instantiated, and simultaneously calls the other afterCreate and so on?

What is the best way to handle these kinds of relationship issues with mirage?

Thanks in Advance!

1

1 Answers

1
votes

Depending on your data needs in each test, you can use traits to give you some more control here. Here's one way you could do it:

// factories/author.js
import { Factory, trait } from 'ember-cli-mirage';

export default Factory.extend({

  name: 'Author name',

  withPosts: trait({

    afterCreate(author, server) {
      server.createList('post', 3, { author });
    }

  })

});

// factories/post.js
import { Factory, trait } from 'ember-cli-mirage';

export default Factory.extend({

  title: 'My first blog post',

  afterCreate(post, server) {
    if (!post.author) {
      server.create('author', { posts: [ post ] });
    }
  }

});

This is basically saying, anytime you create a post, if you didn't pass in an author it will make one. This makes sense because a post can't exist without an author.

But an author can exist without a post. In some tests, you may just need an author, and don't want to worry about creating posts too. The trait lets you do both:

server.create('author'); // just an author
server.create('author', 'withPosts'); // an author with posts

Now you have more flexibility to seed your mock database according to the needs of your test.

Hope that helps!