question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Question] How mock imports with jest

See original GitHub issue

When testing my application, jest can’t mock the imports:

 FAIL  __tests__/common/componnents/Button.test.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    /home/marcos/git/it-happens/mateusapp/appcrm_v2/shared/common/components/CartaoDepartamento/CartaoDepartamento.component.js:21
      return import('../../res/Departamentos/mercearia.svg');
             ^^^^^^

    SyntaxError: Unexpected token import

I’ve tried several things (since I’m new to testing), like using this gist, I created a file named react-native-svg-mock.js inside the project_root/__mock__/ and my jest.config.js looked like this.

// jest.config.js
const {defaults} = require('jest-config');

module.exports = {
    verbose: true,
    moduleFileExtensions:[...defaults.moduleFileExtensions],
    transform: {
        "\\.svg$": "<rootDir>/__mocks__/react-native-svg-mock.js"
      },
    preset: 'react-native',

};

I’ve tried as well configs like this one bellow, since inside the metro.config.js , it’s associated with babelTransformerPath, but when using it, jest complains about a process function missing

// jest.config.js
const {defaults} = require('jest-config');

module.exports = {
    verbose: true,
    moduleFileExtensions:[...defaults.moduleFileExtensions],
    transform: {
        "\\.svg$": require.resolve("react-native-svg-transformer")
      },
    preset: 'react-native',

};

output

yarn run v1.17.3
$ jest
 FAIL  __tests__/common/componnents/Button.test.js
  ● Test suite failed to run

    TypeError: Jest: a transform must export a `process` function.

      1 | import React from 'react'
    > 2 | import VoltarAndroid from './../res/botao_voltar.svg'
        | ^
      3 | import VoltarIos from './../res/back_ios.svg'
      4 | import { Platform, View } from 'react-native'
      5 | 

      at ScriptTransformer._getTransformer (node_modules/@jest/transform/build/ScriptTransformer.js:291:15)
      at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:353:28)
      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:457:40)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
      at Object.<anonymous> (shared/common/components/BackButton.js:2:1)

Can anyone help me to use this module with jest properly?


Edit

How to reproduce the error:

Clone the example repo:

git clone https://github.com/kristerkari/react-native-svg-example

go inside the project folder and add Jest as dependency:

yarn add --dev jest

or using npm

npm install --save-dev jest

create a folder and file with the following structure __test__/app.test.js inside the root folder.

Add the following code to app.test.js:

import Hostgator from "./logos/hostgator.svg";

const sum = (a,b)=> a + b

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

Now that we have a simple test, if we try to run

yarn test

The test won’t passed because because of this import.

If we comment the import as following:

//import Hostgator from "./logos/hostgator.svg";

const sum = (a,b)=> a + b

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

The test will pass.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

9reactions
kristerkaricommented, Aug 10, 2019

I added the documentation to README for mocking the SVG images with Jest. If it does not work for you, please let me know and let’s fix the docs.

https://github.com/kristerkari/react-native-svg-transformer#usage-with-jest

7reactions
pjivers-bomcommented, Apr 12, 2021

If anyone is using require('xxx.svg').default to import an SVG, your svgMock.js should look like the following:

const SvgMock = () => 'SvgMock'
export default SvgMock
Read more comments on GitHub >

github_iconTop Results From Across the Web

How can I mock an ES6 module import using Jest?
The reason that you must have jest.mock at the top of your tests, is internally jest will reorder the jest.mock before the imports....
Read more >
Manual Mocks - Jest
In order to mock properly, Jest needs jest.mock('moduleName') to be in the same scope as the require/import statement.
Read more >
How to mock imported functions with Jest - DEV Community ‍ ‍
To mock an imported function with Jest we use the jest.mock() function. jest.mock() is called with one required argument - the import path...
Read more >
Mocking ES and CommonJS modules with jest.mock() - Medium
You can mock both externally required/imported code, or code passed in through dependency injection. Mocking code passed in through dependency ...
Read more >
solving the jest.mock()+esmodules hoisting problem
So the module first gets mocked, then gets imported. This is cool becase it solves a clear problem; you can't technically write code...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found