Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use setupFiles rather than setupFilesAfterEnv?

Tags:

I see that there are two config options in jest for having some code running before each tests : setupFiles and setupFilesAfterEnv. It seems to me that setupFilesAfterEnv gives more flexibility (I can use jest, beforeEach and so on ...), so I don't understand in what context setupFiles would be more useful. Can someone provide an example where you need to use setupFiles rather than setupFilesAfterEnv ?

Documentation : https://jestjs.io/docs/en/configuration#setupfiles-array

like image 921
Aymeric Bouzy aybbyk Avatar asked Sep 24 '19 12:09

Aymeric Bouzy aybbyk


People also ask

What is setupFilesAfterEnv?

setupFiles will be executed. before the test framework is installed in the environment. setupFilesAfterEnv will be executed. after the test framework has been installed in the environment. That's why the name has AfterEnv.

What is rootDir in Jest?

rootDir [string] Default: The root of the directory containing the package.json or the pwd if no package.json is found. Please provide your exact Jest configuration and mention your Jest, node, yarn/npm version and operating system.

What is Jest config js?

The jest. config. js file is used for configuring Jest, the JavaScript testing library used for writing unit and integration tests in Pup. The modulePaths property tells Jest where it can resolve NPM modules used inside of the code you're testing.


Video Answer


1 Answers

We can see what different between setupFiles and setupFilesAfterEnv from the documentation.

The most important difference will probably be when it is run.

setupFiles will be executed

before the test framework is installed in the environment.

setupFilesAfterEnv will be executed

after the test framework has been installed in the environment.

That's why the name has AfterEnv.

I actually use both of them in my actual project.

In my case, I use the setupFiles to set up fro .env values and use the setupFilesAfterEnv to set up jest configuration like jest.setTimeout(70000)


>> In my case >>>>>>>>>>>>>>>>>>>>>>>

jest.config.js

  setupFiles: ['<rootDir>/tests/settings/env-setup.ts'],   setupFilesAfterEnv: ['<rootDir>/testSetupFile.js'], 

env-setup.ts

import dotenv from 'dotenv'; import path from 'path';  console.log(`============ env-setup Loaded ===========`); dotenv.config({ path: path.resolve(process.cwd(), 'tests', 'settings', '.test.env') }); 

testSetupFile.ts

// Some of the `jest` tests are very slow and cause // timeouts on bitbucket pipeline console.log(`============ testSetupFile Loaded ===========`); jest.setTimeout(70000);  
like image 178
Steve Baek Avatar answered Sep 23 '22 06:09

Steve Baek