How to speed up Jest tests (2024)

How to speed up Jest tests (3)

TDD is awesome. It changes the way we are thinking about programming, it solves tremendous number of problems. However, every test takes time and memory. It is problem I was struggling a lot. Here I will show you couple solutions you should consider having the same problem.

How to check memory usage in jest?

just add flag : ‘ — logHeapUsage’

//package.json
"scripts": {
"test": "jest --logHeapUsage ",
}

Solution 1 — ISOLATED_MODULES

If you use TypeScript tests can take a bit longer since Jest will check types. Actually you can speed this up by skipping types checking.

Open your ‘jest.config.ts’ file (or file you use for jest configuration)

Inside find property ‘transform’

const config: JestConfigWithTsJest = {
transform: {
'^.+\\.(t|j)s$': ['ts-jest', { isolatedModules:true }]
},
}

When you add ‘ { isolatedModules:true }’ tests will run a bit faster.

Solution 2 — Check your globalSetup and setupFilesAfterEnv

Open your ‘jest.config.ts’ file (or file you use for jest configuration)

There are 2 properties :

const config: JestConfigWithTsJest = { 
// many more properties
globalSetup: './test/bootstrap.ts',
setupFilesAfterEnv: ['./test/setup.ts']
// many more properties
}
  • globalSetup will run every time you run ‘npm run test’. In my case it is ‘./test/bootstrap.ts’ file. So it will run function from there once.
  • setupFilesAfterEnv will fire before each test. So if you have 1000 tests, it can run 1000 times after your ‘npm run test’

Now open file from setupFilesAfterEnv and check for unnecessary things there. Some can be move to global setup, everything will work faster.

// setup.ts , so my setupFilesAfterEnv file
afterAll(async () => {
await truncate();
redis.quit();
});
// setup.ts , so my globalSetup file
export default async () => {
//most of those lines were in setupFilesAfterEnv berfore
global._request = request;

const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule]
}).compile();

global.app = moduleFixture.createNestApplication();

setContainer(app);
setGlobalPrefix(app);
initI18(app);

await global.app.init();

global.request = request(app.getHttpServer());

global.i18nService = i18nService;
global.prismaService = app.get<PrismaService>(PrismaService);
global.graph = graph;

await truncate();
};

Actually, in my case (E2E tests)I can leave methods for truncating database, in setupFilesAfterEnv, rest I moved to globalSetup.

Solution 3 — expose-gc

It helped a lot when it comes to memory usage. On my Mac tests are a bit slower but I think it can speed up tests on slow machines/test servers

//package.json
"scripts": {
"test:ci": "node --expose-gc ./node_modules/.bin/jest --logHeapUsage --ci --runInBand",
}

Just add ‘ — expose-gc’ flag. You can also try ‘ — ci’ and ‘ — runInBand’, very often it helps when you use CI

Solution 4— Running only some test (group runner)

Sometimes we need to run only some tests. I wrote article how to do this using jest group runner. You can read more here

Solution 5— in memory db

Some ORMs can support db in memory, so without hiting hard disk. In can increase performance a lot, especially in E2E tests, however you can face some problems with migrations. Not every ORM supports inMemory DB, but here you have code for sequalize:

// sequalize example
let sequelize;
if(process.env.NODE_ENV === 'test') {
sequelize = new Sequelize('sqlite::memory:');
}

Thank you for reading until the end. Before you go:

How to speed up Jest tests (2024)
Top Articles
Pas på med guldsmykker købt i udlandet | Tavex
How to Create a Video Monetization Strategy in 5 Steps [2024 Update]
How To Start a Consignment Shop in 12 Steps (2024) - Shopify
Where To Go After Howling Pit Code Vein
Katie Nickolaou Leaving
Drury Inn & Suites Bowling Green
Tiny Tina Deadshot Build
Canya 7 Drawer Dresser
Compare Foods Wilson Nc
Time in Baltimore, Maryland, United States now
Dte Outage Map Woodhaven
Was ist ein Crawler? | Finde es jetzt raus! | OMT-Lexikon
T Mobile Rival Crossword Clue
My Boyfriend Has No Money And I Pay For Everything
Mustangps.instructure
Self-guided tour (for students) – Teaching & Learning Support
AB Solutions Portal | Login
United Dual Complete Providers
How To Delete Bravodate Account
Mission Impossible 7 Showtimes Near Regal Bridgeport Village
‘Accused: Guilty Or Innocent?’: A&E Delivering Up-Close Look At Lives Of Those Accused Of Brutal Crimes
Betonnen afdekplaten (schoorsteenplaten) ter voorkoming van lekkage schoorsteen. - HeBlad
What Happened To Maxwell Laughlin
Bowie Tx Craigslist
Commodore Beach Club Live Cam
Saatva Memory Foam Hybrid mattress review 2024
Understanding Genetics
Putin advierte que si se permite a Ucrania usar misiles de largo alcance, los países de la OTAN estarán en guerra con Rusia - BBC News Mundo
Costco Gas Hours St Cloud Mn
1979 Ford F350 For Sale Craigslist
Wonder Film Wiki
Pronóstico del tiempo de 10 días para San Josecito, Provincia de San José, Costa Rica - The Weather Channel | weather.com
Tottenham Blog Aggregator
Craigslist Texas Killeen
Rund um die SIM-Karte | ALDI TALK
Kltv Com Big Red Box
Los Amigos Taquería Kalona Menu
Gerber Federal Credit
Chase Bank Cerca De Mí
Missouri State Highway Patrol Will Utilize Acadis to Improve Curriculum and Testing Management
Directions To The Closest Auto Parts Store
Weather In Allentown-Bethlehem-Easton Metropolitan Area 10 Days
Jammiah Broomfield Ig
Tropical Smoothie Address
Zipformsonline Plus Login
St Anthony Hospital Crown Point Visiting Hours
Yosemite Sam Hood Ornament
Paradise leaked: An analysis of offshore data leaks
Erica Mena Net Worth Forbes
Swissport Timecard
Les BABAS EXOTIQUES façon Amaury Guichon
Códigos SWIFT/BIC para bancos de USA
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 5353

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.