GaelF
GaelF

Reputation: 1157

Have Jest return the correct image paths (typescript + react)

I'm writing a React app and I import images the following way:

import image1Src from 'assets/img1.png";

In my tests I would like to do assertions on the <img/> src paths, so for that I'd need the imports to work when running the Jest tests. I've found plenty of solutions to return a hardcoded string, which isn't sufficient because I need to actually test the src paths.

The closest thing I've found is this:

import path from 'path';

// https://github.com/facebook/jest/issues/2838

module.exports = {
    process: (_: unknown, filename: string): string => {
        return `module.exports = '${JSON.stringify(path.basename(filename))}';`;
    },
};

But it doesn't work, it returns the function { process: [Function: process] }.

Any idea?

Upvotes: 1

Views: 1880

Answers (1)

Lin Du
Lin Du

Reputation: 102617

You should use transform configuration.

Note: a transformer is only run once per file unless the file has changed. During the development of a transformer it can be useful to run Jest with --no-cache to frequently delete Jest's cache.

jest.config.js:

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  transform: {
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/examples/68838761/fileTransformer.js',
  },
};

fileTransformer.js:

const path = require('path');

module.exports = {
  process(src, filename, config, options) {
    return 'module.exports = ' + JSON.stringify(filename) + ';';
  },
};

index.test.ts:

//@ts-ignore
import image1Src from './assets/img1.png';

describe('68838761', () => {
  test('should pass', () => {
    console.log(image1Src);
  });
});

Command:

jest -o --no-cache

You will get the absolute file path when importing the assets/img1.png file in the test file. Test result:

 PASS  examples/68838761/index.test.ts (9.171 s)
  68838761
    ✓ should pass (13 ms)

  console.log
    /Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/examples/68838761/assets/img1.png

      at Object.<anonymous> (examples/68838761/index.test.ts:6:13)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.229 s

Upvotes: 2

Related Questions