[英]NodeJS | Jest | Factory Girl | Faker: Faker generating the same values
I'm developing a Node.js API and now I'm creating the tests using supertest for all the routes.我正在开发 Node.js API 现在我正在使用supertest为所有路线创建测试。
I found the best practice is to use the factory-girl and the faker to generate random values for the models.我发现最好的做法是使用factory-girl和faker为模型生成随机值。
Knowing that, I created my factory.js :知道了这一点,我创建了factory.js :
import faker from 'faker/locale/pt_BR';
import { factory } from 'factory-girl';
import User from '../src/app/models/User';
factory.define('User', User, {
name: faker.name.findName(),
email: faker.internet.email(),
password: faker.internet.password(),
});
export default factory;
Its works beautiful when I executed one time:当我执行一次时,它的作品很漂亮:
it('should be able to register', async () => {
const user = await factory.attrs('User');
const response = await request(app)
.post('/users')
.send(user);
expect(response.body).toHaveProperty('id');
});
The line const user = await factory.attrs('User');行const user = await factory.attrs('User'); returns the following model:返回以下 model:
{
name: 'Sra. Dalila Pereira',
email: 'Jlia68@bol.com.br',
password: 'zhpMclO9KwWfhlt'
}
But if I call the same instruction two times, the models will be equals:但是如果我两次调用相同的指令,模型将是相等的:
it('should return all users', async () => {
const user1 = await factory.attrs('User');
await request(app)
.post('/users')
.send(user1);
const user2 = await factory.attrs('User');
await request(app)
.post('/users')
.send(user2);
const response = await request(app)
.get('/users')
.set('Authorization', `Bearer ${token}`);
expect(response.status).toBe(200);
});
Model: user1 Model:用户1
{
name: 'Salvador Costa',
email: 'Warley.Braga@hotmail.com',
password: 'Q4EfvNJv9zulONR'
}
Model: user2 Model:用户2
{
name: 'Salvador Costa',
email: 'Warley.Braga@hotmail.com',
password: 'Q4EfvNJv9zulONR'
}
So when the second post is called an error occurs because the user already exists.因此,当调用第二个帖子时会发生错误,因为用户已经存在。
Do you know what can I do to solve this problem?你知道我能做些什么来解决这个问题吗?
Thanks谢谢
The documentation provides this example:该文档提供了此示例:
// Using objects as initializer
factory.define('product', Product, {
// use sequences to generate values sequentially
id: factory.sequence('Product.id', (n) => `product_${n}`),
// use functions to compute some complex value
launchDate: () => new Date(),
// ...
})
The launchDate
field is being calculated per-call.每次调用都会计算launchDate
字段。
The same should hold true for faker.伪造者也应该如此。 In order to guarantee a fresh value every time, try providing an arrow function.为了保证每次都是新鲜的值,请尝试提供箭头 function。
factory.define('User', User, {
name: () => faker.name.findName(),
email: () => faker.internet.email(),
password: () => faker.internet.password(),
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.