test-utils.js.tpl 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import path from 'path';
  2. import webpack from 'webpack';
  3. import Promise from 'bluebird';
  4. import MemoryFs from 'memory-fs';
  5. const fs = new MemoryFs();
  6. const unitTestFixtures = path.resolve(__dirname, 'fixtures');
  7. /**
  8. *
  9. *
  10. * @param {string} fixtureName
  11. * @param {string} [withQueryString='']
  12. * @returns {string} Absolute path of a file with query that is to be run by a loader.
  13. */
  14. function getFixtureResource(fixtureName, withQueryString = '') {
  15. return `${getFixture(fixtureName)}?${withQueryString}`;
  16. }
  17. /**
  18. *
  19. *
  20. * @param {string} fixtureName
  21. * @returns {string} Absolute path of a file with query that is to be run by a loader.
  22. */
  23. function getFixture(fixtureName) {
  24. return path.resolve(unitTestFixtures, `${fixtureName}.js`);
  25. }
  26. /**
  27. *
  28. *
  29. * @param {Object} withOptions - Loader Options
  30. * @returns {{loader: string, options: Object}}
  31. */
  32. function getLoader(withOptions) {
  33. return [{ loader: path.resolve(__dirname, '../dist/index.js'), options: withOptions }];
  34. }
  35. /**
  36. *
  37. *
  38. * @param {string} exampleName
  39. * @returns {Object|Array} - Returns an object or array of objects representing the webpack configuration options
  40. */
  41. function getExampleConfig(exampleName) {
  42. return require(`../examples/${exampleName}/webpack.config.js`);
  43. }
  44. /**
  45. *
  46. *
  47. * @param {string} exampleName - name of example inside of examples folder
  48. * @returns
  49. */
  50. async function runWebpackExampleInMemory(exampleName) {
  51. const webpackConfig = getExampleConfig(exampleName);
  52. const compiler = webpack(webpackConfig);
  53. compiler.outputFileSystem = fs;
  54. const run = Promise.promisify(compiler.run, { context: compiler });
  55. const stats = await run();
  56. const { compilation } = stats;
  57. const { errors, warnings, assets, entrypoints, chunks, modules } = compilation;
  58. const statsJson = stats.toJson();
  59. return {
  60. assets,
  61. entrypoints,
  62. errors,
  63. warnings,
  64. stats,
  65. chunks,
  66. modules,
  67. statsJson,
  68. };
  69. }
  70. export { getExampleConfig, runWebpackExampleInMemory, fs, getFixtureResource, getLoader, getFixture };