How to use loadBabelConfig method in Jest

Best JavaScript code snippet using jest

config.js

Source: config.js Github

copy

Full Screen

...11 presets.splice(index, 1);12 }13}14/​/​ Tries to load a .babelrc and returns the parsed object if successful15function loadBabelConfig(babelConfigPath) {16 let config;17 if (fs.existsSync(babelConfigPath)) {18 const content = fs.readFileSync(babelConfigPath, 'utf-8');19 try {20 config = JSON5.parse(content);21 config.babelrc = false;22 } catch (e) {23 logger.error(`=> Error parsing .babelrc file: ${e.message}`);24 throw e;25 }26 }27 if (!config) return null;28 /​/​ Remove react-hmre preset.29 /​/​ It causes issues with react-storybook.30 /​/​ We don't really need it.31 /​/​ Earlier, we fix this by runnign storybook in the production mode.32 /​/​ But, that hide some useful debug messages.33 if (config.presets) {34 removeReactHmre(config.presets);35 }36 if (config.env && config.env.development && config.env.development.presets) {37 removeReactHmre(config.env.development.presets);38 }39 return config;40}41/​/​ `baseConfig` is a webpack configuration bundled with storybook.42/​/​ Storybook will look in the `configDir` directory43/​/​ (inside working directory) if a config path is not provided.44export default function(configType, baseConfig, projectDir, configDir) {45 const config = baseConfig;46 /​/​ Search for a .babelrc in project directory, config directory, and storybook47 /​/​ module directory. If found, use that to extend webpack configurations.48 const babelConfigInConfig = loadBabelConfig(path.resolve(configDir, '.babelrc'));49 const babelConfigInProject = loadBabelConfig(path.resolve(projectDir, '.babelrc'));50 const babelConfigInModule = loadBabelConfig('.babelrc');51 let babelConfig = null;52 let babelConfigDir = '';53 if (babelConfigInConfig) {54 logger.info('=> Loading custom .babelrc from config directory.');55 babelConfig = babelConfigInConfig;56 babelConfigDir = configDir;57 } else if (babelConfigInProject) {58 logger.info('=> Loading custom .babelrc from project directory.');59 babelConfig = babelConfigInProject;60 babelConfigDir = projectDir;61 } else {62 babelConfig = babelConfigInModule;63 }64 if (babelConfig) {...

Full Screen

Full Screen

make-cache.js

Source: make-cache.js Github

copy

Full Screen

...71 }72 }73 return configPath74 }75 function loadBabelConfig(editor) {76 if (!configCache.has(editor)) {77 let babelConfig: ?Object = undefined78 const configPath = findConfigFile(editor)79 if (configPath != null) {80 debug("loadBabelConfig", configPath)81 try {82 if (path.extname(configPath) === ".js") {83 const dontCache = {}84 const requireIfTrusted = makeRequire(trusted => {85 if (trusted === false) {86 return undefined87 }88 if (trusted === true) {89 data.delete(editor)90 configCache.delete(editor)91 }92 return dontCache93 })94 /​/​ $FlowExpectError95 const cfg = requireIfTrusted(configPath)96 debug("cfg", cfg)97 babelConfig = typeof cfg === "function" ? cfg() : cfg98 if (babelConfig === dontCache) {99 return undefined100 }101 } else {102 babelConfig = JSON.parse(String(fs.readFileSync(configPath)))103 }104 if (babelConfig) {105 babelConfig.cwd = babelConfig.cwd || path.dirname(configPath)106 const babel = require("@babel/​core")107 babelConfig = babel.loadOptions(babelConfig)108 }109 } catch (e) {110 debug("loadBabelConfig error", e)111 }112 debug("babel config", babelConfig)113 }114 configCache.set(editor, babelConfig)115 }116 return configCache.get(editor)117 }118 function watchEditor(editor) {119 if (!editors.has(editor)) {120 editors.set(editor, null)121 subscriptions.add(122 editor.onDidStopChanging(() => {123 data.delete(editor)124 }),125 )126 }127 }128 return {129 get(editor: TextEditor): Info {130 watchEditor(editor)131 if (!data.has(editor)) {132 data.set(editor, parseCode(editor.getText(), loadBabelConfig(editor)))133 }134 /​/​ $FlowExpectError - Flow thinks it might return null here135 return data.get(editor)136 },137 }...

Full Screen

Full Screen

index.js

Source: index.js Github

copy

Full Screen

...44 filename: Path,45 configString: string,46 {config, instrument, rootDir}: {config: ProjectConfig} & CacheKeyOptions,47 ): string {48 const babelOptions = loadBabelConfig(config.cwd, filename);49 const configPath = [50 babelOptions.config || '',51 babelOptions.babelrc || '',52 ];53 return crypto54 .createHash('md5')55 .update(THIS_FILE)56 .update('\0', 'utf8')57 .update(JSON.stringify(babelOptions.options))58 .update('\0', 'utf8')59 .update(fileData)60 .update('\0', 'utf8')61 .update(path.relative(rootDir, filename))62 .update('\0', 'utf8')63 .update(configString)64 .update('\0', 'utf8')65 .update(configPath.join(''))66 .update('\0', 'utf8')67 .update(instrument ? 'instrument' : '')68 .update('\0', 'utf8')69 .update(process.env.NODE_ENV || '')70 .update('\0', 'utf8')71 .update(process.env.BABEL_ENV || '')72 .digest('hex');73 },74 process(75 src: string,76 filename: Path,77 config: ProjectConfig,78 transformOptions?: TransformOptions,79 ): string | TransformedSource {80 const babelOptions = {...loadBabelConfig(config.cwd, filename).options};81 if (transformOptions && transformOptions.instrument) {82 babelOptions.auxiliaryCommentBefore = ' istanbul ignore next ';83 /​/​ Copied from jest-runtime transform.js84 babelOptions.plugins = babelOptions.plugins.concat([85 [86 babelIstanbulPlugin,87 {88 /​/​ files outside `cwd` will not be instrumented89 cwd: config.rootDir,90 exclude: [],91 },92 ],93 ]);94 }...

Full Screen

Full Screen

babel-jest.js

Source: babel-jest.js Github

copy

Full Screen

...33 filename,34 configString,35 { config, instrument, rootDir }36 ) {37 const babelOptions = loadBabelConfig(38 JSON.parse(configString).cwd,39 filename40 );41 const configPath = [42 babelOptions.config || '',43 babelOptions.babelrc || ''44 ];45 return crypto46 .createHash('md5')47 .update(THIS_FILE)48 .update('\0', 'utf8')49 .update(JSON.stringify(babelOptions.options))50 .update('\0', 'utf8')51 .update(fileData)52 .update('\0', 'utf8')53 .update(path.relative(rootDir, filename))54 .update('\0', 'utf8')55 .update(configString)56 .update('\0', 'utf8')57 .update(configPath.join(''))58 .update('\0', 'utf8')59 .update(instrument ? 'instrument' : '')60 .update('\0', 'utf8')61 .update(process.env.NODE_ENV || '')62 .update('\0', 'utf8')63 .update(process.env.BABEL_ENV || '')64 .digest('hex');65 },66 process(src, filename, config, transformOptions) {67 const babelOptions = { ...loadBabelConfig(config.cwd, filename).options };68 if (transformOptions && transformOptions.instrument) {69 babelOptions.auxiliaryCommentBefore = ' istanbul ignore next ';70 /​/​ Copied from jest-runtime transform.js71 babelOptions.plugins = babelOptions.plugins.concat([72 [73 babelIstanbulPlugin,74 {75 /​/​ files outside `cwd` will not be instrumented76 cwd: config.rootDir,77 exclude: []78 }79 ]80 ]);81 }...

Full Screen

Full Screen

babel_config.test.js

Source: babel_config.test.js Github

copy

Full Screen

...26 ]27 }`,28 },29 });30 const config = loadBabelConfig('.foo');31 expect(config).toEqual({32 babelrc: false,33 plugins: [34 'foo-plugin',35 [36 babelPluginReactDocgenPath,37 {38 DOC_GEN_COLLECTION_NAME: 'STORYBOOK_REACT_CLASSES',39 },40 ],41 ],42 presets: ['env', 'foo-preset'],43 });44 });45 it('should return the config with the extra plugins when `plugins` is not an array.', () => {46 setup({47 files: {48 '.babelrc': `{49 "presets": [50 "env",51 "foo-preset"52 ],53 "plugins": "bar-plugin"54 }`,55 },56 });57 const config = loadBabelConfig('.bar');58 expect(config).toEqual({59 babelrc: false,60 plugins: [61 'bar-plugin',62 [63 babelPluginReactDocgenPath,64 {65 DOC_GEN_COLLECTION_NAME: 'STORYBOOK_REACT_CLASSES',66 },67 ],68 ],69 presets: ['env', 'foo-preset'],70 });71 });72 it('should return the config only with the extra plugins when `plugins` is not present.', () => {73 /​/​ Mock a `.babelrc` config file with no plugins key.74 setup({75 files: {76 '.babelrc': `{77 "presets": [78 "env",79 "foo-preset"80 ]81 }`,82 },83 });84 const config = loadBabelConfig('.biz');85 expect(config).toEqual({86 babelrc: false,87 plugins: [88 [89 babelPluginReactDocgenPath,90 {91 DOC_GEN_COLLECTION_NAME: 'STORYBOOK_REACT_CLASSES',92 },93 ],94 ],95 presets: ['env', 'foo-preset'],96 });97 });98});

Full Screen

Full Screen

jest.config.js

Source: jest.config.js Github

copy

Full Screen

1const { createConfigItem } = require('@babel/​core');2const { loadBabelConfig, loadCoreConfig, loadCoreConfigFiles } = require('wc-bundler');3const babel = loadBabelConfig(loadCoreConfig(loadCoreConfigFiles(undefined)).babel, {4 env: { targets: { node: '12' } },5 typescript: true,6});7makeBabelPluginConfigSerializable(babel.plugins);8makeBabelPluginConfigSerializable(babel.presets);9/​** @type {import('@jest/​types').Config.InitialOptions} */​10const config = {11 coveragePathIgnorePatterns: [/​\/​node_modules\/​/​.source, /​\/​\S*fixture\S*\/​/​.source],12 transform: { [/​\.[jt]sx?$/​.source]: ['babel-jest', babel] },13};14module.exports = config;15/​**16 * Jest 启用 worker 执行测试用例时, babel 的 ConfigItem 无法被序列化传入 worker ,17 * 也无法通过缓存文件共享,因此需要转换一下。...

Full Screen

Full Screen

babel-jest_vx.x.x.js

Source: babel-jest_vx.x.x.js Github

copy

Full Screen

1/​/​ flow-typed signature: 4c5da1c3fe02232aa441a60ecf7ce8cd2/​/​ flow-typed version: <<STUB>>/​babel-jest_v^27.4.6/​flow_v0.130.03/​**4 * This is an autogenerated libdef stub for:5 *6 * 'babel-jest'7 *8 * Fill this stub out by replacing all the `any` types.9 *10 * Once filled out, we encourage you to share your work with the11 * community by sending a pull request to:12 * https:/​/​github.com/​flowtype/​flow-typed13 */​14declare module 'babel-jest' {15 declare module.exports: any;16}17/​**18 * We include stubs for each file inside this npm package in case you need to19 * require those files directly. Feel free to delete any files that aren't20 * needed.21 */​22declare module 'babel-jest/​build' {23 declare module.exports: any;24}25declare module 'babel-jest/​build/​loadBabelConfig' {26 declare module.exports: any;27}28/​/​ Filename aliases29declare module 'babel-jest/​build/​index' {30 declare module.exports: $Exports<'babel-jest/​build'>;31}32declare module 'babel-jest/​build/​index.js' {33 declare module.exports: $Exports<'babel-jest/​build'>;34}35declare module 'babel-jest/​build/​loadBabelConfig.js' {36 declare module.exports: $Exports<'babel-jest/​build/​loadBabelConfig'>;...

Full Screen

Full Screen

jest.babel.js

Source: jest.babel.js Github

copy

Full Screen

1const { createHash } = require('crypto');2const { createTransformer } = require('babel-jest');3const path = require('path')4const { existsSync } = require('fs-extra')5function loadBabelConfig() {6 const babelConfigPath = path.resolve(process.cwd(), 'babel.config')7 if (existsSync(babelConfigPath)) {8 return require(babelConfigPath)9 }10 return {};11}12module.exports = {13 canInstrument: true,14 getCacheKey(sourceText) {15 const babelOptions = loadBabelConfig();16 return createHash('md5')17 .update('\0', 'utf8')18 .update(JSON.stringify(babelOptions))19 .update('\0', 'utf8')20 .update(sourceText)21 .update('\0', 'utf8')22 .update('components')23 .update('\0', 'utf8')24 .digest('hex');25 },26 process(sourceText, sourcePath, transformOptions) {27 const babelOptions = loadBabelConfig();28 const babelJest = createTransformer(babelOptions);29 return babelJest.process(sourceText, sourcePath, transformOptions);30 },...

Full Screen

Full Screen

StackOverFlow community discussions

Questions
Discussion

Testing a redux action

jest mock implementation is not working with require(&#39;&#39;)

How to use different jest.config.js for unit and component tests?

&#39;command not found: jest&#39;

How to test a React component that update over time with Jest and Enzyme?

react-testing-library: some portion of debug&#39;s output is not visible

Jest URL.createObjectURL is not a function

Is it possible to use Jest with multiple presets at the same time?

How to test if the type of the result is a javascript &#39;function&#39; in Jest?

Using environment variables in React application

You haven't mocked the API call and since it won't success without a mock, the action dispatched when the promise resolves is not fired. You can use fetchMock to mock the API call. Once you do that correctly, your test will work

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';
import fetch from 'node-fetch';

export const foo = () => {
  return (dispatch) => {
    dispatch(actionOne());
    return fetch(`api/sampleUrl`)
      .then(r => r.json())
      .then(json => dispatch(actionTwo(json)))
      .catch(error => handleError(error));
  };
};

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

beforeEach(() => {
  store = mockStore({});
  fetchMock.restore()
});

describe('sample test', () => {
  test('validates foo complex action', () => {

    fetchMock.getOnce('api/sampleUrl', {
      body: { sample: ['do something'] }
    })

    const expectedActions = [
      {type: actionTypes.ACTION_ONE},
      {type: actionTypes.ACTION_TWO},
    ];

    return store.dispatch(actions.foo())
      .then(() => {
        expect(store.getActions())
          .toEqual(expectedActions);
      });
  });
});
https://stackoverflow.com/questions/54677579/testing-a-redux-action

Blogs

Check out the latest blogs from LambdaTest on this topic:

Top 11 JavaScript Frameworks For 2019

An extensive number of programming languages are being used worldwide today, each having its own purpose, complexities, benefits and quirks. However, it is JavaScript that has without any doubt left an indelible and enduring impression on the web, to emerge as the most popular programming language in the world for the 6th consecutive year.

Using ChatGPT for Test Automation

ChatGPT broke all Internet records by going viral in the first week of its launch. A million users in 5 days are unprecedented. A conversational AI that can answer natural language-based questions and create poems, write movie scripts, write social media posts, write descriptive essays, and do tons of amazing things. Our first thought when we got access to the platform was how to use this amazing platform to make the lives of web and mobile app testers easier. And most importantly, how we can use ChatGPT for automated testing.

19 Best Practices For Automation testing With Node.js

Node js has become one of the most popular frameworks in JavaScript today. Used by millions of developers, to develop thousands of project, node js is being extensively used. The more you develop, the better the testing you require to have a smooth, seamless application. This article shares the best practices for the testing node.in 2019, to deliver a robust web application or website.

13 Best JavaScript Frameworks For 2020

According to stackoverflow’s developer survey 2020, JavaScript is the most commonly used language for the 8th year straight with 67.7% people opting for it. The major reason for its popularity is the fact that JavaScript is versatile and can be used for both frontend and backend development as well as for testing websites or web applications as well.

Cypress vs Selenium – Which Is Better ?

Selenium is one of the most prominent automation frameworks for functional testing and web app testing. Automation testers who use Selenium can run tests across different browser and platform combinations by leveraging an online Selenium Grid, you can learn more about what Is Selenium? Though Selenium is the go-to framework for test automation, Cypress – a relatively late entrant in the test automation game has been catching up at a breakneck pace.

Jest Testing Tutorial

LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.

Chapters

  1. What is Jest Framework
  2. Advantages of Jest - Jest has 3,898,000 GitHub repositories, as mentioned on its official website. Learn what makes Jest special and why Jest has gained popularity among the testing and developer community.
  3. Jest Installation - All the prerequisites and set up steps needed to help you start Jest automation testing.
  4. Using Jest with NodeJS Project - Learn how to leverage Jest framework to automate testing using a NodeJS Project.
  5. Writing First Test for Jest Framework - Get started with code-based tutorial to help you write and execute your first Jest framework testing script.
  6. Jest Vocabulary - Learn the industry renowned and official jargons of the Jest framework by digging deep into the Jest vocabulary.
  7. Unit Testing with Jest - Step-by-step tutorial to help you execute unit testing with Jest framework.
  8. Jest Basics - Learn about the most pivotal and basic features which makes Jest special.
  9. Jest Parameterized Tests - Avoid code duplication and fasten automation testing with Jest using parameterized tests. Parameterization allows you to trigger the same test scenario over different test configurations by incorporating parameters.
  10. Jest Matchers - Enforce assertions better with the help of matchers. Matchers help you compare the actual output with the expected one. Here is an example to see if the object is acquired from the correct class or not. -

|<p>it('check_object_of_Car', () => {</p><p> expect(newCar()).toBeInstanceOf(Car);</p><p> });</p>| | :- |

  1. Jest Hooks: Setup and Teardown - Learn how to set up conditions which needs to be followed by the test execution and incorporate a tear down function to free resources after the execution is complete.
  2. Jest Code Coverage - Unsure there is no code left unchecked in your application. Jest gives a specific flag called --coverage to help you generate code coverage.
  3. HTML Report Generation - Learn how to create a comprehensive HTML report based on your Jest test execution.
  4. Testing React app using Jest Framework - Learn how to test your react web-application with Jest framework in this detailed Jest tutorial.
  5. Test using LambdaTest cloud Selenium Grid - Run your Jest testing script over LambdaTest cloud-based platform and leverage parallel testing to help trim down your test execution time.
  6. Snapshot Testing for React Front Ends - Capture screenshots of your react based web-application and compare them automatically for visual anomalies with the help of Jest tutorial.
  7. Bonus: Import ES modules with Jest - ES modules are also known as ECMAScript modules. Learn how to best use them by importing in your Jest testing scripts.
  8. Jest vs Mocha vs Jasmine - Learn the key differences between the most popular JavaScript-based testing frameworks i.e. Jest, Mocha, and Jasmine.
  9. Jest FAQs(Frequently Asked Questions) - Explore the most commonly asked questions around Jest framework, with their answers.

Run Jest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful