简体   繁体   English

使用节点生成唯一的测试数据

[英]Generating unique test data with node

I'm currently using chance.js to generate test data. 我目前正在使用chance.js生成测试数据。 For example, I can generate a random email and use it to test my models. 例如,我可以生成一个随机电子邮件,并用它来测试我的模型。

My problem is that I need to ensure some fields on my models are unique eg email on the user model. 我的问题是我需要确保模型上的某些字段是唯一的,例如用户模型上的电子邮件。 Does chance ensure that it doesn't generate the same email twice? chance确保它不会两次生成相同的电子邮件吗?

I'd be willing to use faker as an alternative but I couldn't find out if faker offered this functionality. 我愿意使用faker作为替代,但是我不知道faker提供了此功能。

There is a unique function at chance.js which also support comparator functionality From the change.js docs : chance.js有一个独特的功能,它还支持change.js文档中的比较器功能:

The comparator used to determine whether a generated item is in the list of already generated items. 比较器,用于确定生成的项目是否在已生成的项目列表中。 By default the comparator just checks to see if the newly generated item is in the array of already generated items. 默认情况下,比较器仅检查新生成的项目是否在已生成项目的数组中。 This works for most simple cases (such as chance.state()) but will not work if the generated item is an object (because the Array.prototype.indexOf() method will not work on an object since 2 objects will not be strictly equal, ===, unless they are references to the same object). 这适用于大多数简单情况(例如偶然事件(state.state())),但如果生成的项是对象则将不起作用(因为Array.prototype.indexOf()方法将不适用于一个对象,因为严格来讲2个对象不是严格意义上的等于===,除非它们是对同一对象的引用)。

chance.unique(chance.currency, 2, {
    comparator: function(err, val) {
        return arr.reduce(function(acc, item) {
            return acc || (item.code === val.code);
        }, false);
    }
});

check the docs for more details... 检查文档以获取更多详细信息...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM