Skip to content

Repository files navigation

Gofakeit Plugin

A powerful autofill plugin for form field automation using the Gofakeit API.

Tests Coverage

gofakeit_js_usage.mov

Try the Live Demo - Demo page

Quick Start

npm install gofakeit

ES Modules (Recommended)

import { Autofill } from 'gofakeit';

// Create an autofill instance and fill all form fields
const autofill = new Autofill();
await autofill.fill();

// Or target specific elements
await autofill.fill('#myForm'); // Target by ID
await autofill.fill('.form-container'); // Target by class
Browser Usage (UMD/IIFE)

Browser (UMD)

<script src="https://unpkg.com/gofakeit/dist/gofakeit.umd.js"></script>
<script>
  const autofill = new Gofakeit.Autofill();
  await autofill.fill();
</script>

Browser (IIFE)

<script src="https://unpkg.com/gofakeit/dist/gofakeit.iife.js"></script>
<script>
  const autofill = new Gofakeit.Autofill();
  await autofill.fill();
</script>

Features

  • 🎯 Smart Detection: Automatically detects and fills form fields based on context and labels
  • 🌐 Function Generation: Generate data using the Gofakeit API functions
  • 🔍 Function Search: Intelligent function discovery using natural language queries
  • 🔒 Deterministic Types: email, tel, url, password, and standard autocomplete tokens map to exact generators instead of fuzzy search
  • ⚙️ Resolution Controls: Score floor/margin, excluded functions, per-type overrides, and custom resolvers
  • 🧩 Framework Safe: Values are written through native setters so React onChange and Vue v-model observe them
  • 👁️ Transparent: See exactly which function was chosen and why (resolvedBy, score, reasons)
  • 🎨 Visual Feedback: Function badges show which gofakeit function was used
  • 📅 Date/Time Support: All date/time input types with min/max constraints
  • 🔢 Number Support: Number and range inputs with min/max parameters
  • 🔢 Pattern Support: Pattern inputs using regex
  • ✅ Form Controls: Checkboxes, radio buttons, and select elements
  • 🚫 Error Handling: Visual feedback for invalid functions
  • 🔧 TypeScript: Full TypeScript support with type definitions

Supported Input Types

  • Text inputs: text, email, password, tel, url, search - Auto-detected via search API
  • Form controls: checkbox, radio, select - Uses appropriate API functions
  • Date/Time: date, time, datetime-local, month, week - With min/max constraints
  • Numbers: number, range - With min/max parameters
  • Color: color - Uses hexcolor function for hex color values

Unsupported Input Types

  • File inputs: file - Currently Not supported by the Gofakeit API
  • Image inputs: image - Currently Not supported by the Gofakeit API

Advanced Usage

import { Autofill } from 'gofakeit';

// Create an autofill instance with default settings
const autofill = new Autofill({
  mode: 'auto', // 'auto' or 'manual'(data-gofakeit only)
  stagger: 50, // Delay between field fills (ms)
  badges: 3000, // How long to show function badges (ms)
  debug: true, // Enable debug logging
  dryRun: false, // Resolve/generate without writing to the DOM
  onStatusChange: (status, elements) => {
    // Track autofill progress
    console.log(`Status: ${status}, Elements: ${elements.length}`);
  },
  onFunctionDetermined: (element, result) => {
    // Called whenever a function is chosen (result is present for search hits)
    console.log(element.name, element.function, element.resolvedBy, element.score);
  }
});

// Autofill all form fields on the page
await autofill.fill();

// Autofill using string selectors
await autofill.fill('#myForm'); // Target by ID
await autofill.fill('.form-container'); // Target by class
await autofill.fill('.form-section input[type="email"]'); // Complex CSS selector

// Autofill all fields within a specific container
const form = document.getElementById('myForm');
await autofill.fill(form);

// Autofill a single form element
const input = document.getElementById('email');
await autofill.fill(input);

// Autofill with a specific function override
await autofill.fill('#myForm', 'password'); // Use 'password' function for all elements
await autofill.fill(input, 'uuid'); // Use 'uuid' function for this specific element

// Autofill with function and custom parameters
await autofill.fill('#myForm', 'password', { length: 12, special: true }); // Custom password params
await autofill.fill(input, 'number', { min: 1, max: 100 }); // Custom number range

Status Callbacks

You can track the autofill process using the onStatusChange callback:

import { Autofill, AutofillStatus } from 'gofakeit';

const autofill = new Autofill({
  onStatusChange: (status, elements) => {
    console.log(`Status: ${status}, Elements: ${elements.length}`);

    switch (status) {
      case AutofillStatus.STARTING:
        console.log('Autofill process starting');
        break;
      case AutofillStatus.FOUND:
        console.log('Form elements found and identified');
        break;
      case AutofillStatus.DETERMINED:
        console.log('Functions determined for each element');
        break;
      case AutofillStatus.GENERATED:
        console.log('Values generated from the API');
        break;
      case AutofillStatus.SET:
        console.log('Values applied to form elements');
        break;
      case AutofillStatus.COMPLETED:
        console.log('Autofill process completed successfully');
        break;
      case AutofillStatus.ERROR:
        console.log('An error occurred during autofill');
        break;
    }
  }
});

await autofill.fill();

Status Values

The onStatusChange callback receives the following status values:

  • STARTING - Autofill process is starting
  • FOUND - Form elements have been found and identified
  • DETERMINED - Functions have been determined for each element
  • GENERATED - Values have been generated from the API
  • SET - Values have been applied to the form elements
  • COMPLETED - Autofill process finished successfully
  • ERROR - An error occurred during the autofill process

The callback also receives the current elements array, which contains all the form elements being processed with their current state (function, value, error, etc.).

Function Override

You can override the automatic function detection by specifying a gofakeit function name as the second parameter:

// Use a specific function for all elements in a form
await autofill.fill('#myForm', 'password');

// Use a specific function for a single element
const emailInput = document.getElementById('email');
await autofill.fill(emailInput, 'uuid');

// Use a specific function for elements matching a CSS selector
await autofill.fill('input[type="date"]', 'date');

// Use a function with custom parameters
await autofill.fill('#myForm', 'password', {
  length: 12,
  special: true,
  upper: true
});

// Use a function with custom parameters for specific elements
await autofill.fill('input[type="number"]', 'number', {
  min: 1,
  max: 100
});

This is particularly useful when you need:

  • Consistent data types across multiple fields
  • Specific formatting requirements
  • Testing with known function outputs
  • Overriding the automatic detection for complex input types
  • Custom parameters for gofakeit functions (e.g., password length, number ranges, date ranges)

Resolution Controls

When an element has no exact generator, the library asks the search API for the best function. You can constrain that decision with AutofillSettings:

const autofill = new Autofill({
  // Force an exact function per input type
  typeFunctions: { text: 'word', number: 'number' },

  // Reject weak matches: fall back to the type function instead
  minSearchScore: 500, // absolute floor
  minSearchScoreMargin: 1.25, // top must beat the runner-up by 25% (default)

  // Never allow these generators to be chosen
  excludedFunctions: ['email_text'],

  // Fully custom resolver; receives the default fallback
  resolveFunction: (element, fallback) => {
    if (element.getAttribute('name') === 'coupon') return 'uuid'
    return fallback
  },
});

Resolution runs in this order, from most to least specific:

  1. fill(target, functionName) override
  2. data-gofakeit="<function>"
  3. pattern -> regex
  4. resolveFunction
  5. typeFunctions[type]
  6. Standard autocomplete token (for example given-name -> firstname)
  7. Built-in type fallback (email -> email, checkbox -> bool, ...)
  8. Fuzzy search, constrained by the score floor/margin, exclusions, and structural guards
  9. The built-in type fallback if the search is rejected or unavailable

Every resolved element exposes function, resolvedBy (override, data-attribute, pattern, custom, type, autocomplete, search, or fallback), and score when it came from search. The onFunctionDetermined callback is invoked for each one.

Autocomplete Mapping

Standard autocomplete tokens are resolved before any fuzzy search, which makes common forms far more predictable:

Token Function Token Function
given-name firstname street-address street
family-name lastname address-level2 city
email email address-level1 state
tel phone postal-code zip
organization company country country
username username new-password password
cc-number creditcardnumber cc-csc creditcardcvv

Framework Compatibility

Values are written through the native HTMLInputElement / HTMLTextAreaElement / HTMLSelectElement setters and then input and change events are dispatched. This means frameworks that track value changes (React onChange, Vue v-model) observe autofilled values as if the user typed them.

Dry Run

Set dryRun: true to resolve functions and generate values without touching the DOM. The results are still available on state.elements (and via onStatusChange), which is useful for previews and debugging:

const autofill = new Autofill({ dryRun: true });
const result = await autofill.fill();
console.log(result.elements.map(el => [el.name, el.function, el.value]));

Transport Options

The API client can be pointed at a different host and tuned for timeouts/retries:

const autofill = new Autofill({
  apiBaseUrl: 'https://api.gofakeit.com/funcs',
  timeout: 15000, // ms per request
  retries: 2, // retried on network errors, 429, and 5xx
});

Constraint Awareness

Generated values respect the element's own constraints: text is truncated to maxlength and padded to minlength, and number/range values are clamped to min/max and snapped to step.

API Functions

The plugin provides direct access to the Gofakeit API with clear input/output examples.

Single Function Call

import { fetchFunc } from 'gofakeit';

// Input: Function name
const result = await fetchFunc('email');

// Output: Success response
{
  result: "john.doe@example.com"
}

// Input: Function with parameters
const result = await fetchFunc('password', {
  length: 12,
  upper: true,
  lower: true,
  numeric: true,
  special: true
});

// Output: Success response
{
  result: "MyP@ssw0rd123!"
}

// Input: Invalid function
const result = await fetchFunc('invalidFunction');

// Output: Error response
{
  error: "Function not found"
}

Multiple Function Calls

import { fetchFuncMulti } from 'gofakeit';

// Input: Array of function requests
const results = await fetchFuncMulti([
  { func: 'name' },
  { func: 'email' },
  { func: 'randomstring', params: { strs: ['first', 'second', 'third'] }},
  { func: 'number', params: { min: 1, max: 100 }}
]);

// Output: Array of results
{
  results: [
    { id: "req_0", value: "John Smith" },
    { id: "req_1", value: "john.smith@example.com" },
    { id: "req_2", value: "second" },
    { id: "req_3", value: 42 }
  ]
}

// Input: Empty array
const results = await fetchFuncMulti([]);

// Output: Error response
{
  error: "No functions provided"
}

Function Search API

The fetchFuncSearch function allows you to find the best gofakeit function for your needs by searching with natural language queries. It supports both single requests and batch requests.

Single Search Request

import { fetchFuncSearch } from 'gofakeit';

// Input: Single search request (id is optional)
const searchResult = await fetchFuncSearch({
  queries: ['email address', 'contact email']
});

// Output: Single result object (transformed by our client)
{
  results: {
    id: "",
    results: [
      {
        name: "email",
        score: 7751
      },
      {
        name: "email_text",
        score: 2202
      }
    ]
  }
}

// Input: With optional id for identification
const searchResultWithId = await fetchFuncSearch({
  id: 'email_search',
  queries: ['email address', 'contact email']
});

// Output: Same structure with your provided id (transformed by our client)
{
  results: {
    id: "email_search",
    results: [
      {
        name: "email",
        score: 7751
        ]
      }
    ]
  }
}

Batch Search Requests

// Input: Array of search requests
// IDs are optional but helpful for identifying results
const searchResults = await fetchFuncSearch([
  { id: 'email_search', queries: ['email', 'contact'] },
  { id: 'name_search', queries: ['first name', 'given name'] },
  { id: 'phone_search', queries: ['phone number', 'telephone'] }
]);

// Output: Array of result objects (transformed by our client)
{
  results: [
    {
      id: "email_search",
      results: [
        {
          name: "email",
          score: 2495
        },
        {
          name: "email_text",
          score: 1101
        }
      ]
    },
    {
      id: "name_search",
      results: [
        {
          name: "firstname",
          score: 8108
          ]
        },
        {
          name: "name",
          score: 2755
          ]
        }
      ]
    },
    {
      id: "phone_search",
      results: [
        {
          name: "phone",
          score: 4458
          ]
        },
        {
          name: "phoneformatted",
          score: 2411
          ]
        }
      ]
    }
  ]
}

// Input: Empty array
const searchResults = await fetchFuncSearch([]);

// Output: Error response
{
  error: "No search requests provided"
}

Using Search Results

// Process search results
if (searchResult.results && !searchResult.error) {
  const bestMatch = searchResult.results.results[0];
  console.log(`Best function: ${bestMatch.name}`);
  console.log(`Confidence score: ${bestMatch.score}`);
  console.log(`Why it matched: ${bestMatch.reasons?.join(', ') ?? 'n/a'}`);

  // Use the best match function
  const data = await fetchFunc(bestMatch.name);
  console.log(`Generated data: ${data.result}`);
}

Real-World Examples

Here are practical examples showing how to use the API functions in real applications:

Example 1: User Registration Form

import { fetchFuncMulti, fetchFuncSearch } from 'gofakeit';

// Step 1: Search for appropriate functions
const searchResults = await fetchFuncSearch([
  { id: 'first_name', queries: ['first name', 'given name'] },
  { id: 'last_name', queries: ['last name', 'surname', 'family name'] },
  { id: 'email', queries: ['email address', 'contact email'] },
  { id: 'phone', queries: ['phone number', 'telephone', 'mobile'] }
]);

// Step 2: Extract function names from search results
const functions = searchResults.results.map(result => result.results[0].name);
// Result: ['firstname', 'lastname', 'email', 'phone']

// Step 3: Generate data using the found functions
const userData = await fetchFuncMulti([
  { func: functions[0] }, // firstname
  { func: functions[1] }, // lastname
  { func: functions[2] }, // email
  { func: functions[3] }  // phone
]);

// Output: Complete user data
{
  results: [
    { id: "req_0", value: "John" },
    { id: "req_1", value: "Smith" },
    { id: "req_2", value: "john.smith@example.com" },
    { id: "req_3", value: "+1-555-123-4567" }
  ]
}

Example 2: Product Information

// Input: Generate product data with specific parameters
const productData = await fetchFuncMulti([
  {
    func: 'product',
    params: { category: 'electronics' }
  },
  {
    func: 'price',
    params: { min: 10, max: 1000 }
  },
  {
    func: 'number',
    params: { min: 1, max: 100 }
  }
]);

// Output: Product information
{
  results: [
    { id: "req_0", value: "Wireless Bluetooth Headphones" },
    { id: "req_1", value: 249.99 },
    { id: "req_2", value: 42 }
  ]
}

Example 3: Address Generation

// Input: Generate complete address
const addressData = await fetchFuncMulti([
  { func: 'street' },
  { func: 'city' },
  { func: 'state' },
  { func: 'zip' },
  { func: 'country' }
]);

// Output: Complete address
{
  results: [
    { id: "req_0", value: "123 Main Street" },
    { id: "req_1", value: "New York" },
    { id: "req_2", value: "NY" },
    { id: "req_3", value: "10001" },
    { id: "req_4", value: "United States" }
  ]
}

Example 4: Error Handling

// Input: Mix of valid and invalid functions
const mixedResults = await fetchFuncMulti([
  { func: 'email' },           // Valid
  { func: 'invalidFunction' }, // Invalid
  { func: 'name' }             // Valid
]);

// Output: Results with error handling
{
  results: [
    { id: "req_0", value: "john.doe@example.com" },
    { id: "req_1", error: "Function not found" },
    { id: "req_2", value: "John Smith" }
  ]
}

// Handle errors in your code
mixedResults.results.forEach((result, index) => {
  if (result.error) {
    console.error(`Request ${index} failed: ${result.error}`);
  } else {
    console.log(`Request ${index} success: ${result.value}`);
  }
});

Advanced Input Type Features

The plugin provides intelligent handling for complex input types with constraints

Data Attributes

You can control autofill behavior using HTML data attributes:

<!-- Specify a specific function -->
<input type="text" data-gofakeit="email" />

<!-- Enable autofill (always filled, regardless of mode) -->
<input type="text" data-gofakeit="true" />

<!-- Exclude field from autofill -->
<input type="text" data-gofakeit="false" />

<!-- No attribute: Only filled in Auto Mode (default) -->
<input type="text" />

Error Handling

The plugin provides comprehensive error handling with visual feedback:

<!-- Invalid function names will show error badges -->
<input type="text" data-gofakeit="invalidFunction" />

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Run the test suite
  6. Submit a pull request

Tests

Tests must exercise real usage. Do not add mocks or fetch stubs:

  • No vi.spyOn(globalThis, 'fetch'), no vi.doMock, no fixture-based fetch stubs.
  • Tests run against the live gofakeit API and real DOM APIs, so they need network access.
  • Prefer asserting observable library state (function, resolvedBy, score, reasons) over watching network calls.
  • Settings that force a deterministic outcome (unreachable score thresholds, exclusions) make live-API assertions stable.

Run the suite with npm test, or use npm run type-check and npm run lint to check the code without network access.

Changelog

When shipping a version bump or finishing user-facing work that will go into a release, update CHANGELOG.md in the same change set.

Follow the Keep a Changelog style already used in the file:

  • Add or extend the section for the version being released (e.g. ## [2.5.0])
  • Use ### Added, ### Changed, ### Fixed, or ### Removed as appropriate
  • Prefer concise bullets; link related GitHub issues when known
  • Skip pure chore/noise (dependency bumps, dist rebuilds) unless they affect consumers

Release

Run npm run release to cut a release. It runs tests, type-checks, builds, updates the version and lockfile, publishes to npm, commits the release files (package.json, package-lock.json, dist, docs, CHANGELOG.md), and optionally creates and pushes a git tag.

License

MIT License - see LICENSE file for details.

About

Javascript plugin for Gofakeit

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages