vendredi 14 septembre 2018

problems testing require.context with jest

I´m trying to test React with Jest. The components import other components from a index file that maps all the components, this file uses the require.context function which jest doesn´t like. I was trying to come up with a solution mocking the requires to the index file but I´m having problems to make it work.

TypeError: require.context is not a function

> 1 | const req = require.context(".", true, /\.\/[^/]+\/[^/]+\/index\.js$/);

The index file:

const req = require.context(".", true, /\.\/[^/]+\/[^/]+\/index\.js$/);

req.keys().forEach(key => {
  const componentName = key.replace(/^.+\/([^/]+)\/index\.js/, "$1");
  module.exports[componentName] = req(key).default;
});

I import the components like this:

import { AuthFormWrapper, Button } from '../../../components';

The moduleNameMapper option in jest configuration:

"moduleNameMapper": {
      "^components$": "<rootDir>/__tests__/setup/__mocks__/componentMock.js"
    },

The mock component file:

import React from 'react'
import PropTypes from 'prop-types'

module.exports = new Proxy({}, {
    get: (target, property) => {
        const Mock = props => <span>{props.children}</span>;

        Mock.displayName = property;
        Mock.propTypes = {
            children: PropTypes.any,
        };

        return Mock
    },
});

Aucun commentaire:

Enregistrer un commentaire