dimanche 21 février 2021

How to turn of module reloading in JEST?

I am using Jest to testing express REST api written in express.js and typescript using ts-jest. My problem is Jest loads app module (express) in every test suite, it lasts only 3-4 seconds, but there is ~80 test suites each containing a multiple test cases.

My first thought was to remove jest.resetModules() from global afterAll() function, but it didn't helped. Is there another way how to change this behaviour or it is feature by design?

setup.ts

import { sequelize } from '../src/db/models'
import seeds from '../src/db/seeders/test'

// multiple mocks of services
jest.mock('../some/custom/module/mocks')


beforeAll(async () => {
    await sequelize.sync({ force: true }) // basically drop db and create clean one
    await seeds() // seed database with data
})

afterAll(async () => {
    jest.clearAllMocks()
    // jest.resetModules() //! This line was removed
    await sequelize.close()
    global.gc()
})

jest.setTimeout(10000)

global.ts

import { createJwt } from '../src/utils/authorization'

export default async () => {
// create some acces tokens and add to process.env
    process.env.jwttoken = await createJwt({ uid: 1 }, { audience: 'users' })
}

jest.config.js

module.exports = {
transform: {
    '^.+\\.ts?$': 'ts-jest'
},
roots: [
    '<rootDir>/tests/'
],
moduleFileExtensions: [
    'ts',
    'js'
],
setupFilesAfterEnv: [
    '<rootDir>/tests/setup.ts'
],
globalSetup: '<rootDir>/tests/global.ts',
testEnvironment: 'node'
}

example test

import supertest from 'supertest'
import app from '../../../../../src/app'

describe(`[GET] ${endpoint(':id')})`, () => {
const request = supertest(app).  // every time jest hits this line in test, it load app again

it('no authorization token | code 401', async () => {
    const response = await request.get('/something')
        .set('Content-Type', 'application/json')
    expect(response.status).toBe(401)
})

start script

POSTGRESQL_URL=postgresql://postgres:root@127.0.0.1:5432/database JWT_SECRET=secret node --expose-gc \"./node_modules/jest/bin/jest.js\" --runInBand --passWithNoTests --logHeapUsage

Aucun commentaire:

Enregistrer un commentaire