keepcalculator

06 Numbers and Powers

Loki Visual Regression Testing in React: How-To

Card No. 06·88407 · Updated · Standard formula, shown below

This guide shows you how to set up and use Loki to catch unintended UI changes in your React components. You’ll take screenshots of your components, compare them against a baseline, and get a clear pass/fail report. You’ll need a React project (CRA, Next.js, or Vite) and Node.js installed.

What You’ll Need

  • A React project with a package manager (npm or yarn).
  • Node.js 12 or newer.
  • Chrome or Chromium installed (Loki uses Puppeteer, which downloads its own Chromium by default).
  • Basic familiarity with the command line.

Step-by-Step

  1. Install Loki and its React adapter. Run npm install --save-dev loki @loki/plugin-react (or yarn add --dev loki @loki/plugin-react). This installs the core tool and the plugin that lets you capture React components directly.
  2. Add a Loki configuration file. Create loki.config.js in your project root. Start with a minimal config that tells Loki where your stories or components live. For a CRA project, you can use:
    module.exports = {
      configurations: {
        'chrome.laptop': {
          target: 'chrome.docker',
          width: 1366,
          height: 768,
        },
      },
      chromeSelector: '.loki-story',
      plugins: ['@loki/plugin-react'],
    };

    If you use Storybook, you’ll instead point to your Storybook URL (see Tips).

  3. Create a test file for your components. Create a file like src/__loki__/Button.test.js. Use the @loki/plugin-react API to render a component and take a screenshot:
    import React from 'react';
    import { render } from '@testing-library/react';
    import { toMatchImageSnapshot } from '@loki/plugin-jest';
    import Button from '../components/Button';
    
    expect.extend({ toMatchImageSnapshot });
    
    test('Button renders correctly', async () => {
      const { container } = render(<Button>Click me</Button>);
      await page.screenshot({ path: 'loki/button.png' });
      expect(fs.readFileSync('loki/button.png')).toMatchImageSnapshot();
    });

    Note: This example uses Jest and the plugin-jest matcher. If you prefer plain Loki, you can use the CLI commands directly (see below).

  4. Run Loki for the first time to generate baselines. In your terminal, run npx loki update. This captures screenshots of all your components and stores them in the .loki folder as the baseline. You’ll see output like ✔ Captured 5 screenshots.
  5. Make a change to your component. For example, change the button’s background color from blue to green. This simulates a real code change.
  6. Run Loki to test against the baseline. Run npx loki test. Loki will take new screenshots and compare them pixel-by-pixel with the baseline. If there’s a difference, it will report a failure and save the diff image in .loki/diff.
  7. Review the diff report. After the test, open .loki/report.html in your browser. It shows a table with each component, a thumbnail of the baseline, the current screenshot, and the diff (highlighted in red). This is where you decide if the change is intentional or a bug.
  8. Approve intentional changes. If the change is intentional (e.g., you updated the design), run npx loki approve. This updates the baseline with the new screenshots, so future tests will compare against the new look.
  9. Integrate into your CI pipeline (optional). Add a script to your package.json: "test:visual": "loki test". Then in your CI config (e.g., GitHub Actions), run npm run test:visual after your unit tests. Loki will fail the build if any screenshot differs.

Common Mistakes

  • Forgetting to update baselines after intentional changes. If you don’t run loki approve, every subsequent test will fail because the baseline is outdated.
  • Running tests on different screen sizes without configuring them. Loki uses the configurations block to define viewport sizes. If you test on your laptop (1366px) but CI runs on a different size, you’ll get false diffs.
  • Including dynamic content in screenshots. Dates, random IDs, or animated elements will cause flaky tests. Mock them or freeze time.
  • Not ignoring the .loki folder in git. You should commit the baseline images, but not the temp/diff folders. Add .loki/diff and .loki/tmp to your .gitignore.

Tips

  • Use Storybook if you have many components – Loki has first-class support via @loki/plugin-storybook. You just point Loki to your Storybook URL and it captures all stories automatically.
  • Run npx loki test --storiesFilter "Button" to test only a subset of components during development.
  • Set a threshold to ignore minor pixel differences (e.g., anti-aliasing). In your config, add diffingEngine: 'pixelmatch' and diffingOptions: { threshold: 0.1 }.
  • Use Docker for consistent rendering across machines. Set target: 'chrome.docker' in your config – this ensures the same Chromium version and fonts everywhere.
  • Keep your baseline images in version control. This lets you see when a visual change was introduced.

Troubleshooting

  • Loki fails to launch Chrome. Run npx loki update --chromeFlags="--no-sandbox" or set chromeFlags in your config. On Linux CI, you may need to install dependencies: apt-get install -y gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget.
  • Tests pass locally but fail in CI. This is almost always a rendering environment difference. Use Docker target in CI, and ensure your CI has the same font rendering libraries. Also check that your CI’s screen resolution doesn’t affect layout – set explicit widths in your config.
  • Loki reports “Cannot find module ‘@loki/plugin-react'”. Make sure you installed it with --save-dev and that your config file is in the project root. If using a monorepo, you may need to specify the path in the config.
  • Diff images are all red, even for unchanged components. This often happens when the browser version changed. Run npx loki update to regenerate baselines with the current browser.
  • Loki hangs or times out. Increase the timeout in your config: timeout: 60000. Also check if you have any infinite animations – they can prevent the screenshot from being taken.

Frequently Asked Questions

Can I use Loki with TypeScript?

Yes. Loki works with TypeScript projects. You just need to compile your tests or use ts-node. The plugin doesn’t care about the language, only the rendered output.

Does Loki work with Next.js?

Yes. You can either use Storybook with Loki, or create a custom test page that renders your components. Since Loki uses Puppeteer, it can load any URL, so you can point it to a local Next.js dev server.

How do I ignore a specific component from testing?

Use the --storiesFilter option to exclude it, or in your test file, simply don’t write a test for that component. If using Storybook, you can add a loki: { skip: true } parameter to the story.

What’s the difference between loki test and loki update?

loki test compares current screenshots to the baseline and fails if there are differences. loki update overwrites the baseline with new screenshots – use it when you want to accept the current state as the new reference.

Can I test responsive designs with Loki?

Yes. Define multiple configurations in your loki.config.js with different widths. Loki will take a separate screenshot for each configuration, and you’ll see separate diffs for each.

Is Loki free to use?

Yes, Loki is open-source (MIT license). You can use it in commercial projects without cost.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →