2017-06-29 91 views
0

我有一个页面有多个AJAX调用到服务器。现在,我正在用Mirage嘲笑数据以用于测试目的。为此,我使用工厂。Ember Mirage模型:对于多个hasMany和belongsTo

我有工厂在页面呈现过程中使用的所有模型。所有的模型都有很多关系,很少有模型有许多和belongsTo,其他模型有很多单独的。

我在网上找到了使用这些协会后创建钩子。

我的疑问是:

在海市蜃楼型号author.js有:

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

同样,在海市蜃楼型号post.js有:

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

我的疑问是,赢得”它是一个递归调用,在每个afterCreate钩子之后,另一个模型正在实例化,并同时调用另一个afterCreate等?

用幻影来处理这类关系问题的最好方法是什么?

在此先感谢!

回答

0

根据您在每次测试中的数据需求,您可以使用traits为您提供更多控制。这里是你可以做的一种方式:

// 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 ] }); 
    } 
    } 

}); 

这基本上是说,任何时候你创建一个post,如果你没有一个作家会作出一个通过。这是有道理的,因为没有作者就不能存在帖子。

但是作者可以没有帖子而存在。在一些测试中,您可能只需要一位作者,并且不想担心创建帖子。该特性可以让你一举两得:

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

现在你有更多的灵活性,根据测试的需要,你的种子模拟数据库。

希望有帮助!