Appearance
用法
¥Usage
Node.js
使用 Faker 就像从 @faker-js/faker
导入它一样简单。
¥Using Faker is as easy as importing it from @faker-js/faker
.
js
import { faker } from '@faker-js/faker';
// or, if desiring a different locale
// import { fakerDE as faker } from '@faker-js/faker';
const randomName = faker.person.fullName(); // Rowan Nikolaus
const randomEmail = faker.internet.email(); // Kassandra.Haley@erich.biz
js
const { faker } = require('@faker-js/faker');
// or, if desiring a different locale
// const { fakerDE: faker } = require('@faker-js/faker');
const randomName = faker.person.fullName(); // Rowan Nikolaus
const randomEmail = faker.internet.email(); // Kassandra.Haley@erich.biz
有关选择和自定义语言环境的更多信息,请参阅我们的 本地化指南。
¥For more information on selecting and customizing a locale, please refer to our Localization Guide.
浏览器
¥Browser
如果你想自己尝试,你可以通过 Ctrl + Shift + J
/F12
打开浏览器控制台。
¥If you want to try it yourself, you can open your browser console via Ctrl + Shift + J
/ F12
.
在我们的网站上,你可以将 faker 加载到浏览器控制台中
¥On our website, you can load faker into the browser console
通过使用
await enableFaker()
¥by using
await enableFaker()
或使用以下代码:
¥or using the following code:
js
const { faker } = await import('https://esm.sh/@faker-js/faker');
const randomName = faker.person.fullName(); // Amber Keebler
const randomEmail = faker.internet.email(); // Norma13@hotmail.com
某些网站可能有防止下载外部代码的保护措施,开发服务器通常可以正常工作。或者,你可以创建一个简单的 html 文件并使用浏览器打开它:
¥Some websites may have protections against downloading external code, dev servers usually work fine. As an alternative, you can create a simple html file and open it with your browser:
html
<script type="module">
import { faker } from 'https://esm.sh/@faker-js/faker';
// Caitlyn Kerluke
const randomName = faker.person.fullName();
// Rusty@arne.info
const randomEmail = faker.internet.email();
document.getElementById('name').value = randomName;
document.getElementById('email').value = randomEmail;
</script>
<input id="name" />
<input id="email" />
注释
使用浏览器非常适合实验👍。但是,由于 Faker 使用所有字符串来生成虚假数据,Faker 是一个很大的包。它是 > 5 MiB
最小化的。请避免在你的 Web 应用中部署完整的 Faker 包。
¥Using the browser is great for experimenting 👍. However, due to all of the strings Faker uses to generate fake data, Faker is a large package. It's > 5 MiB
minified. Please avoid deploying the full Faker package in your web app.
CDN/Deno
js
import { faker } from 'https://esm.sh/@faker-js/faker';
const randomName = faker.person.fullName(); // Willie Bahringer
const randomEmail = faker.internet.email(); // Tomasa_Ferry14@hotmail.com
注释
强烈建议在 Deno 中导入库时使用版本标签,例如:import { faker } from "https://esm.sh/@faker-js/faker@v9.7.0"
。
¥It is highly recommended to use version tags when importing libraries in Deno, e.g: import { faker } from "https://esm.sh/@faker-js/faker@v9.7.0"
.
替代 CDN 链接
¥Alternative CDN links
esm:
cjs:
TypeScript 支持
¥TypeScript Support
我们假设你使用 TypeScript(严格模式)。你可以在没有它的情况下使用 Faker,但我们没有针对错误参数类型的专用错误消息。
¥We assume that you use TypeScript (strict mode). You can use Faker without it, but we don't have dedicated error messages for wrong parameter types.
为了让 Faker 正常工作,你需要检查这些 compilerOptions
是否在你的 tsconfig
文件中正确设置:
¥In order to have Faker working properly, you need to check if these compilerOptions
are set correctly in your tsconfig
file:
json
{
"compilerOptions": {
"moduleResolution": "Bundler", // "Node10", "Node16" or "NodeNext"
"strict": true // Optional, but recommended
}
}
可重现的结果
¥Reproducible results
通常,Faker 每次使用时都会给你不同的随机值。
¥Normally Faker will give you different random values each time it is used.
ts
faker.music.genre(); // "Soul"
faker.music.genre(); // "Reggae"
如果你想要一致的结果,你可以设置自己的种子:
¥If you want consistent results, you can set your own seed:
ts
faker.seed(123);
const firstRandom = faker.number.int();
// Setting the seed again resets the sequence.
faker.seed(123);
const secondRandom = faker.number.int();
console.log(firstRandom === secondRandom);
注释
当升级到新版本的 Faker 时,你可能会获得相同种子的不同值,因为基础数据(名称、单词等列表)可能已更改。
¥When upgrading to a new version of Faker, you may get different values for the same seed, as the underlying data (lists of names, words etc) may have changed.
有几种使用相对日期的方法,设置随机种子不足以获得可重现的结果,例如:faker.date.past
、faker.date.future
、faker.date.birthdate
、faker.date.recent
、faker.date.soon
和 faker.git.commitEntry
。这是因为这些方法默认在 "today" 之前或之后创建日期,而 "today" 取决于代码的运行时间。要解决此问题,你可以将固定参考日期指定为日期或字符串,例如:
¥There are a few methods which use relative dates for which setting a random seed is not sufficient to have reproducible results, for example: faker.date.past
, faker.date.future
, faker.date.birthdate
, faker.date.recent
, faker.date.soon
and faker.git.commitEntry
. This is because these methods default to creating a date before or after "today", and "today" depends on when the code is run. To fix this, you can specify a fixed reference date as a Date or string, for example:
ts
// creates a date soon after 2023-01-01
faker.date.soon({ refDate: '2023-01-01T00:00:00.000Z' });
或者,你也可以为所有这些方法设置一个默认参考日期:
¥or alternatively you can set a default reference date for all these methods:
ts
// affects all future faker.date.* calls
faker.setDefaultRefDate('2023-01-01T00:00:00.000Z');
简单的数据生成
¥Simple data generation
Faker 提供了一个 simpleFaker
,可用于生成不基于任何语言环境的数据,如数字和字符串。还有像 arrayElement
或 multiple
这样的助手可用。
¥Faker provides a simpleFaker
that can be used to generate data that are not based on any locales like numbers and strings.\ Also helpers like arrayElement
or multiple
are available.
如果你只想生成例如 uuid
用于你的测试环境,但不想/不需要启动/加载完整的 Faker 实例,该实例将包含至少 500KB 的区域设置数据。
¥This is useful if you just want to generate e.g. uuid
s for your test environment, but don't want/need to initiate/load a full Faker instance, which would include at least 500KB of locale data.
ts
import { simpleFaker } from '@faker-js/faker';
const uuid = simpleFaker.string.uuid();
在 API 文档 中查看有关 SimpleFaker
的更多信息。
¥See more about SimpleFaker
in the API docs.
创建复杂对象
¥Create complex objects
Faker 主要为原语生成值。这是因为在现实世界中,大多数对象模式看起来非常不同。因此,如果你想创建一个对象,你很可能需要为其编写一个工厂函数。
¥Faker mostly generates values for primitives. This is because in the real world, most object schemas simply look very different. So, if you want to create an object, you most likely need to write a factory function for it.
对于我们的示例,我们使用 TypeScript 来强类型化我们的模型。我们将使用的模型如下所述:
¥For our example, we use TypeScript to strongly type our model. The models we will use are described below:
ts
import type { SexType } from '@faker-js/faker';
type SubscriptionTier = 'free' | 'basic' | 'business';
interface User {
_id: string;
avatar: string;
birthday: Date;
email: string;
firstName: string;
lastName: string;
sex: SexType;
subscriptionTier: SubscriptionTier;
}
如你所见,我们的 User
模型可能与你代码库中的模型完全不同。需要注意的一件事是 subscriptionTier
属性,因为它不仅仅是一个字符串,而只是 SubscriptionTier
类型('free'
或 'basic'
或 'business'
)中定义的字符串之一。此外,在实际情况下,你的模型不应依赖于第三方库的类型(在本例中为 SexType
)。
¥As you can see, our User
model probably looks completely different from the one you have in your codebase. One thing to keep an eye on is the subscriptionTier
property, as it is not simply a string, but only one of the strings defined in the SubscriptionTier
type ('free'
or 'basic'
or 'business'
). Also, in a real scenario, your model should not depend on a type of a third party library (SexType
in this case).
让我们创建我们的第一个用户工厂函数:
¥Let's create our first user factory function:
ts
import { faker } from '@faker-js/faker';
interface User { ... }
function createRandomUser(): User {
return {
_id: faker.string.uuid(),
avatar: faker.image.avatar(),
birthday: faker.date.birthdate(),
email: faker.internet.email(),
firstName: faker.person.firstName(),
lastName: faker.person.lastName(),
sex: faker.person.sexType(),
subscriptionTier: faker.helpers.arrayElement(['free', 'basic', 'business']),
};
}
const user = createRandomUser();
此时,我们有一个可以完美运行的函数,可用于大多数目的。但我们可以更进一步。目前,所有属性都是随机生成的。这可能会导致产生一些不良值。例如:sex
属性的值为 'female'
,而 firstName
为 'Bob'
。
¥At this point, we have a perfectly working function that will work for most purposes. But we can take this a step further. Currently, all properties are just randomly generated. This can lead to some undesirable values being produced. For example: The sex
property having value 'female'
while firstName
is 'Bob'
.
让我们重构我们当前的代码:
¥Let's refactor our current code:
ts
import { faker } from '@faker-js/faker';
function createRandomUser(): User {
const sex = faker.person.sexType();
const firstName = faker.person.firstName(sex);
const lastName = faker.person.lastName();
const email = faker.internet.email({ firstName, lastName });
return {
_id: faker.string.uuid(),
avatar: faker.image.avatar(),
birthday: faker.date.birthdate(),
email,
firstName,
lastName,
sex,
subscriptionTier: faker.helpers.arrayElement(['free', 'basic', 'business']),
};
}
const user = createRandomUser();
如你所见,我们改变了生成值的顺序。首先,我们生成一个 sex
值,将其用作生成 firstName
的输入。然后我们生成 lastName
。在这里,我们也可以将 sex
值作为参数传入,但在我们的用例中,没有女性姓氏与男性姓氏不同的特殊情况。通过首先执行此操作,我们能够将两个名称传递到 email
生成函数中。这允许根据提供的参数使值更合理。
¥As you can see, we changed the order in which we generate our values. First, we generate a sex
value to use it as input for the generation of firstName
. Then we generate the lastName
. Here, we could also pass in the sex
value as argument, but in our use-case there are no special cases in where a female last name would differ from a male one. By doing this first, we are able to pass both names into the email
generation function. This allows the value to be more reasonable based on the provided arguments.
与使用 uuid
实现的 _id
属性不同,_id
属性的重复几率很低,而 email
函数更容易产生重复,尤其是在调用参数相似的情况下。我们有一个专门的指南页面来生成 唯一值。
¥Unlike the _id
property that uses an uuid
implementation, which has a low chance of duplicates, the email
function is more likely to produce duplicates, especially if the call arguments are similar. We have a dedicated guide page on generating unique values.
上面的示例演示了如何生成复杂对象。为了更好地控制特定属性的值,你可以引入 overwrites
、options
或类似参数:
¥The example above demonstrates how to generate complex objects. To gain more control over the values of specific properties, you can introduce overwrites
, options
or similar parameters:
ts
import { faker } from '@faker-js/faker';
function createRandomUser(overwrites: Partial<User> = {}): User {
const {
_id = faker.string.uuid(),
avatar = faker.image.avatar(),
birthday = faker.date.birthdate(),
sex = faker.person.sexType(),
firstName = faker.person.firstName(sex),
lastName = faker.person.lastName(),
email = faker.internet.email({ firstName, lastName }),
subscriptionTier = faker.helpers.arrayElement([
'free',
'basic',
'business',
]),
} = overwrites;
return {
_id,
avatar,
birthday,
email,
firstName,
lastName,
sex,
subscriptionTier,
};
}
const user = createRandomUser();
const userToReject = createRandomUser({ birthday: new Date('2124-10-20') });
潜在的 options
参数可用于:
¥A potential options
parameter could be used to:
控制包含哪些可选属性,
¥control which optional properties are included,
控制如何合并或替换嵌套元素和数组,
¥control how nested elements and arrays are merged or replaced,
或指定要为嵌套列表生成的项目数。
¥or specify the number of items to generate for nested lists.
恭喜,你现在应该能够创建任何你想要的复杂对象了。假装快乐🥳。
¥Congratulations, you should now be able to create any complex object you desire. Happy faking 🥳.