How to use the random function from faker

Find comprehensive JavaScript faker.random code examples handpicked from public code repositorys.

faker.random is a module in the Faker library that generates random values for various data types.

2
3
4
5
6
7
8
9
10
11

module.exports = () => {
  const numberCompanies = range(0, 5)
  const populateCompany = compose(
    map(() => ({
      id: faker.random.uuid(),
      name: faker.company.companyName(),
      contact: faker.phone.phoneNumber(),
      address: faker.address.streetAddress(),
      tin: faker.finance.iban(),
fork icon141
star icon687
watch icon25

2
3
4
5
6
7
8
9
10
11
function createBrands(num, { brandUrls }) {
  const brands = []

  for (let i = 0; i < num; i++) {
    brands.push({
      brandId: faker.random.uuid(),
      brandLogo: brandUrls[i % brandUrls.length],
      brandName: faker.name.findName(),
      brandQty: faker.random.number({ min: 1, max: 999 }),
    })
fork icon20
star icon72
watch icon6

+ 31 other calls in file

How does faker.random work?

The faker.random module is responsible for generating various types of random data, such as numbers, words, and characters, using different methods based on the data type requested. The methods are designed to return the same value each time they are called with the same parameters, making the results of a test or simulation predictable.

6
7
8
9
10
11
12
13
14
15
module.exports = {
  get: jest.fn().mockImplementation(key => {
    if (!cache[key]) {
      switch(key) {
      case 'uid':
        cache[key] = faker.random.number()
        break
      case 'auth_token':
        cache[key] = faker.random.uuid()
        break
fork icon18
star icon56
watch icon23

+ 5 other calls in file

11
12
13
14
15
16
17
18
19
20
function populate(gender = 'masculino', memberOrAssist = 'Assistente') {
    const member = {
        name: faker.name.findName(),
        address: faker.address.streetAddress(),
        email: faker.internet.email(),
        status: faker.random.boolean(),
        gender: gender,
        birth: formatISO(faker.date.between(new Date(01, 01, 1940), new Date()), 'yyyy-MM-dd'),
        cellphone: '67998882011',
        obs: faker.lorem.sentence(),
fork icon8
star icon37
watch icon3

+ 15 other calls in file

Ai Example

1
2
3
4
5
const faker = require("faker");

const randomNum = faker.random.number({ min: 0, max: 100 });

console.log(randomNum); // Output: e.g. 42

14
15
16
17
18
19
20
21
22
23
const obj = {
        plugin_id: 'zc_reminder',
        organization_id: 'darwin_organization',
        collection_name: 'reminders',
        payload: {
                title: faker.random.word(),
                description: faker.random.words(),
                assignees: faker.name.firstName(),
                creator: faker.name.findName(),
                startDate: faker.date.recent(),
fork icon65
star icon14
watch icon11

+ 7 other calls in file

126
127
128
129
130
131
132
133
134
135
`random_values.js`

```js
const faker = require('faker');

let number = faker.random.number();
console.log(number);

let uuid = faker.random.uuid();
console.log(uuid);
fork icon34
star icon134
watch icon9

+ 15 other calls in file

8
9
10
11
12
13
14
15
16
17
    image: faker.image.imageUrl(),
    name: faker.lorem.word(10),
    price: faker.datatype.number(900),
    ratingValue: faker.datatype.number(5),
    reviewCount: faker.datatype.number(100),
    sku: faker.random.alphaNumeric(15),
    tabletProp: 'tablet',
});

const MOCK_TABLETS = Array.from({ length: TOTAL_TABLETS }, createRandomTablet);
fork icon24
star icon264
watch icon9

148
149
150
151
152
153
154
155
156
157
const response = {
  status: getStatusCode(transactionDoc.status),
  headers: {
    'Content-type': 'text/html'
  },
  timestamp: new Date(requestTime.getTime() + faker.random.number({ min: 30, max: 1200 }))
}

if (response.status >= 500) {
  response.error = {
fork icon60
star icon53
watch icon35

239
240
241
242
243
244
245
246
247
248
  <h3>Приклад</h3>

  <pre><code class="javascript" data-trim>
describe('.applyPayment', function() {
  beforeEach(function *() {
    this.sum = faker.random.number(1000) + 1;

    this.card = yield factory.create('card', {
      userId: this.user.id
    });
fork icon4
star icon7
watch icon6

176
177
178
179
180
181
182
183
184
185
this.include('email', tr.transliterate(`${name[0]}.${name[1]}`).replace(/ /g, '').toLowerCase() + '@example.com');

let salt = random(2, 8);
let password = this.password === undefined ? randomItem(this.datasets.common.passwords) : this.genPassword();
this.include('login', {
  uuid: faker.random.uuid(),
  username: randomItem(this.datasets.common.user1) + randomItem(this.datasets.common.user2) + range(100, 999),
  password,
  salt:   salt,
  md5:    crypto.createHash('md5').update(password + salt).digest('hex'),
fork icon251
star icon0
watch icon34

+ 13 other calls in file

6
7
8
9
10
11
12
13
14
15
return Object.assign({
  comments: [],
  created_at: new Date(),
  deleted_at: null,
  html: lorem,
  id: faker.random.number(),
  is_accepted: false,
  is_locked: false,
  is_read: false,
  is_subscribed: false,
fork icon29
star icon0
watch icon0

+ 5 other calls in file

5
6
7
8
9
10
11
12
13
14
for (let i = 0; i < 50; i++) {
    str += faker.name.firstName() +
    ';' + faker.name.lastName() +
    ';' + faker.internet.email() +
    ';' + faker.name.jobTitle() +
    ';' + faker.random.locale() +
    '\r\n'
}

fs.writeFileSync('test.csv', str);
fork icon8
star icon32
watch icon5

13
14
15
16
17
18
19
20
21
22
  avatar: faker.image.avatar(),
  cover: faker.image.image(),
  bio: faker.lorem.sentence(),
  location: faker.address.city(),
  following: faker.random.number(1000),
  followers: faker.random.number(10000),
},
time: faker.date.recent(10),
tweetContent: faker.lorem.sentences(8),
likes: faker.random.number(500),
fork icon3
star icon5
watch icon6

+ 25 other calls in file

162
163
164
165
166
167
168
169
170
171
},
email: function name(params) {
   return  Faker.internet.email();
},
number: function(num) {
   return Faker.random.number(num); 
},
range: function(start, end) {
    return _.random(start,end);
},
fork icon1
star icon4
watch icon4

+ 3 other calls in file

88
89
90
91
92
93
94
95
module.exports = faker;

/////////

function makeTransCorr() {
  trans = faker.random.uuid();
  corr = _.random(0, 1) === 0 ? trans : faker.random.uuid();
}
fork icon0
star icon4
watch icon11

+ 7 other calls in file

267
268
269
270
271
272
273
274
275
276
})
beforeEach(() => {
    payload = {
        id: receipt.id,
        data:  {
            printableNumber: faker.random.alphaNumeric(32),
        },
    }
    anotherPayload = {
        id: anotherReceipt.id,
fork icon12
star icon32
watch icon10

+ 44 other calls in file

45
46
47
48
49
50
51
52
53
beforeAll(async () => {
    adminClient = await makeLoggedInAdminClient()
    supportClient = await makeClientWithSupportUser()
    userClient = await makeClientWithNewRegisteredAndLoggedInUser()
    anonymousClient = await makeClient()
    sender = { dv: 1, fingerprint: faker.random.alphaNumeric(8) }
    const [o10n] = await createTestOrganization(adminClient)
    dummyO10n = o10n
})
fork icon12
star icon32
watch icon10

+ 8 other calls in file

8
9
10
11
12
13
14
15
16
17
'recipients',
[
  {
    name: faker.name.findName(),
    street: faker.address.streetName(),
    number: faker.random.number(),
    state: faker.address.state(),
    city: faker.address.city(),
    zip_code: faker.address.zipCode(),
    created_at: new Date(),
fork icon3
star icon6
watch icon3

+ 9 other calls in file

192
193
194
195
196
197
198
199
200
201

describe('Resident', () => {
    test('resident: can create MeterReadings in his unit', async () => {
        const adminClient = await makeLoggedInAdminClient()
        const userClient = await makeClientWithResidentAccessAndProperty()
        const unitName = faker.random.alphaNumeric(8)
        const accountNumber = faker.random.alphaNumeric(8)
        const [resident] = await createTestResident(adminClient, userClient.user, userClient.property, {
            unitName,
        })
fork icon12
star icon32
watch icon10

+ 335 other calls in file

248
249
250
251
252
253
254
255
256
const client = await makeEmployeeUserClientWithAbilities({
    canManageMeters: true,
})
const [resource1] = await MeterResource.getAll(client, { id: COLD_WATER_METER_RESOURCE_ID })
const [resource2] = await MeterResource.getAll(client, { id: HOT_WATER_METER_RESOURCE_ID })
const number = faker.random.alphaNumeric(5)

await createTestMeter(client, client.organization, client.property, resource1, { number })
const [meter] = await createTestMeter(client, client.organization, client.property, resource2, { number })
fork icon12
star icon32
watch icon10

+ 27 other calls in file