typescriptreact-nativejestjsexpo

react-native-vector-icons/MaterialIcons jest-expo snapshot test error with typescript


I learning jest, writing my first snapshot tests for components using react-native & expo. I can run the test without the Icon component from 'react-native-vector-icons/MaterialIcons' inside my component. However when I attempt to run a test with the aforementioned Icon component I get the following error:

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

  at Object.get Text [as Text] (node_modules/react-native/Libraries/react-native/react-native-implementation.js:118:12)
  at Icon.render (node_modules/@expo/vector-icons/build/vendor/react-native-vector-icons/lib/create-icon-set.js:120:58)
  at finishClassComponent (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7618:31)
  at updateClassComponent (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7568:24)
  at beginWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:9043:16)

  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log "Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/functio
n (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might 
have mixed up default and named imports.

Check the render method of `Icon`.
    in Icon (created by Icon)
    in Icon".

My code for the test is as follows:

import React from 'react'
import * as Icon from 'react-native-vector-icons/MaterialIcons'
import renderer from 'react-test-renderer'

it('Renders an icon', () => {
  const tree = renderer.create(
    <Icon.default
    size={20}
    color={ 'grey' }
    name={ true ? 'check-box' : 'check-box-outline-blank' }
  />
  ).toJSON()
  expect(tree).toMatchSnapshot();
})

My jest configuration in package.json is like this:

"jest": {
    "preset": "jest-expo",
    "transformIgnorePatterns": [
      "node_modules/(?!((jest-)?react-native|react-clone-referenced-element|expo(nent)?|@expo(nent)?/.*|react-navigation|react-native-vector-icons|@unimodules))"
    ],
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "android.ts",
      "android.tsx"
    ]
  },

The components function fine outside of tests.


Solution

  • After reading the jest documentation more carefully I have found a workaround, using mocks.

    Simply adding the following to the test seems to do the trick:

    jest.mock('react-native-vector-icons/MaterialIcons', () => 'Icon')