|
| 1 | +// Polyfill for webpack's require.context used by some components (tests run in Node) |
| 2 | +// This must run before any modules that expect require.context are imported. |
| 3 | +if (typeof require.context === 'undefined' || typeof (global && global.require && global.require.context) === 'undefined') { |
| 4 | + /* eslint-disable global-require, consistent-return */ |
| 5 | + const path = require('path'); |
| 6 | + const fs = require('fs'); |
| 7 | + |
| 8 | + const makeContext = (base = '.', scanSubdirs = false, regExp = /.*/) => { |
| 9 | + const absoluteBase = path.resolve(__dirname, base); |
| 10 | + const modules = {}; |
| 11 | + |
| 12 | + try { |
| 13 | + const walk = (dir) => { |
| 14 | + fs.readdirSync(dir).forEach((file) => { |
| 15 | + const fullPath = path.join(dir, file); |
| 16 | + const stat = fs.statSync(fullPath); |
| 17 | + if (stat.isDirectory()) { |
| 18 | + if (scanSubdirs) walk(fullPath); |
| 19 | + return; |
| 20 | + } |
| 21 | + const relPath = `./${path.relative(absoluteBase, fullPath).replace(/\\/g, '/')}`; |
| 22 | + if (!regExp || regExp.test(relPath)) { |
| 23 | + // We'll return a simple module-like object with a `default` property |
| 24 | + // that points to the relative path. Tests only need a truthy src. |
| 25 | + modules[relPath] = { default: relPath }; |
| 26 | + } |
| 27 | + }); |
| 28 | + }; |
| 29 | + |
| 30 | + if (fs.existsSync(absoluteBase)) { |
| 31 | + walk(absoluteBase); |
| 32 | + } |
| 33 | + } catch (e) { |
| 34 | + // ignore errors, leave modules empty |
| 35 | + } |
| 36 | + |
| 37 | + const resolver = (key) => modules[key]; |
| 38 | + resolver.keys = () => Object.keys(modules); |
| 39 | + return resolver; |
| 40 | + }; |
| 41 | + |
| 42 | + try { |
| 43 | + require.context = makeContext; |
| 44 | + } catch (e) { |
| 45 | + // ignore |
| 46 | + } |
| 47 | + try { |
| 48 | + if (typeof global !== 'undefined') { |
| 49 | + if (typeof global.require === 'undefined') global.require = require; |
| 50 | + global.require.context = makeContext; |
| 51 | + } |
| 52 | + } catch (e) { |
| 53 | + // ignore |
| 54 | + } |
| 55 | + /* eslint-enable global-require, consistent-return */ |
| 56 | +} |
| 57 | + |
1 | 58 | // jest-dom adds custom jest matchers for asserting on DOM nodes. |
2 | 59 | // allows you to do things like: |
3 | 60 | // expect(element).toHaveTextContent(/react/i) |
|
0 commit comments