You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
run before test and run mongo server and set environment variables till jest executation not complete
constdotenv=require("dotenv");// Path to your .env.test filedotenv.config({path: ".env.test"});// Connect to MongoDBrequire("mongoose").connect(process.env.DB_URI).catch((err)=>{console.error("Error connecting to MongoDB",err);process.exit(1);});
jest.teardown.js
execute after jest testcases complete
constmongoose=require("mongoose");const{ exec }=require("child_process");module.exports=async()=>{awaitmongoose.connection.close();awaitmongoose.disconnect();constreportPath="./reports/jest-stare/index.html";switch(process.platform){case"darwin": // macOSexec(`open ${reportPath}`);break;case"win32": // Windowsexec(`start ${reportPath}`);break;default: // Linux and othersexec(`xdg-open ${reportPath}`);break;}process.exit(0);};
jest.config.js
/** * For a detailed explanation regarding each configuration property, visit: * https://jestjs.io/docs/configuration *//** @type {import('jest').Config} */constconfig={// All imported modules in your tests should be mocked automatically// automock: false,// Stop running tests after `n` failures// bail: 0,// The directory where Jest should store its cached dependency information// cacheDirectory: "/tmp/jest_rt",// Automatically clear mock calls, instances, contexts and results before every testclearMocks: true,// Indicates which provider should be used to instrument code for coveragecoverageProvider: "v8",// A list of reporter names that Jest uses when writing coverage reportscoverageReporters: ["json","text","lcov","clover"],// An array of directory names to be searched recursively up from the requiring module's locationmoduleDirectories: ["node_modules"],// An array of file extensions your modules usemoduleFileExtensions: ["js","mjs","cjs",// "jsx",// "ts",// "tsx","json","node",],// Indicates whether the coverage information should be collected while executing the testcollectCoverage: true,// The directory where Jest should output its coverage filescoverageDirectory: "./reports/coverage",// Use this configuration option to add custom reporters to Jestreporters: ["default",["jest-stare",{resultDir: "reports/jest-stare",reportTitle: "jest-stare!",additionalResultsProcessors: ["jest-junit"],coverageLink: "../coverage/lcov-report/index.html",jestStareConfigJson: "jest-stare.json",jestGlobalConfigJson: "globalStuff.json",},],],// The glob patterns Jest uses to detect test filestestMatch: ["**/__tests__/**/*.[jt]s?(x)","**/?(*.)+(spec|test).[tj]s?(x)"],// An array of regexp pattern strings that are matched against all test paths, matched tests are skippedtestPathIgnorePatterns: ["/node_modules/"],// Whether to use watchman for file crawlingwatchman: false,// Path to setup filesetupFiles: ["./jest.setup.js"],// Adjust the path according to where you placed your setup fileglobalTeardown: "./jest.teardown.js",};module.exports=config;
For More Configurations
/** @type {import('jest').Config} */constconfig={// All imported modules in your tests should be mocked automaticallyautomock: false,// Stop running tests after `n` failuresbail: 1,// The directory where Jest should store its cached dependency informationcacheDirectory: "/tmp/jest_rt",// Automatically clear mock calls, instances, contexts and results before every testclearMocks: true,// Indicates whether the coverage information should be collected while executing the testcollectCoverage: true,// An array of glob patterns indicating a set of files for which coverage information should be collectedcollectCoverageFrom: ["src/**/*.{js,jsx,ts,tsx}"],// The directory where Jest should output its coverage filescoverageDirectory: "coverage",// An array of regexp pattern strings used to skip coverage collectioncoveragePathIgnorePatterns: ["/node_modules/","/tests/"],// Indicates which provider should be used to instrument code for coveragecoverageProvider: "v8",// A list of reporter names that Jest uses when writing coverage reportscoverageReporters: ["json","text","lcov","clover"],// An object that configures minimum threshold enforcement for coverage resultscoverageThreshold: {global: {branches: 80,functions: 80,lines: 80,statements: 80,},},// A path to a custom dependency extractordependencyExtractor: "path/to/dependencyExtractor.js",// Make calling deprecated APIs throw helpful error messageserrorOnDeprecated: true,// The default configuration for fake timersfakeTimers: {enableGlobally: true,},// Force coverage collection from ignored files using an array of glob patternsforceCoverageMatch: ["**/ignored/**"],// A path to a module which exports an async function that is triggered once before all test suitesglobalSetup: "./globalSetup.js",// A path to a module which exports an async function that is triggered once after all test suitesglobalTeardown: "./globalTeardown.js",// A set of global variables that need to be available in all test environmentsglobals: {__DEV__: true,},// The maximum amount of workers used to run your testsmaxWorkers: "50%",// An array of directory names to be searched recursively up from the requiring module's locationmoduleDirectories: ["node_modules","src"],// An array of file extensions your modules usemoduleFileExtensions: ["js","jsx","ts","tsx","json","node"],// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single modulemoduleNameMapper: {"^@src/(.*)$": "<rootDir>/src/$1",},// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loadermodulePathIgnorePatterns: ["/dist/"],// Activates notifications for test resultsnotify: true,// An enum that specifies notification modenotifyMode: "failure-change",// A preset that is used as a base for Jest's configurationpreset: "ts-jest",// Run tests from one or more projectsprojects: ["<rootDir>/project1","<rootDir>/project2"],// Use this configuration option to add custom reporters to Jestreporters: ["default","jest-junit"],// Automatically reset mock state before every testresetMocks: true,// Reset the module registry before running each individual testresetModules: true,// A path to a custom resolverresolver: "path/to/customResolver.js",// Automatically restore mock state and implementation before every testrestoreMocks: true,// The root directory that Jest should scan for tests and modules withinrootDir: "./",// A list of paths to directories that Jest should use to search for files inroots: ["<rootDir>/src"],// Allows you to use a custom runner instead of Jest's default test runnerrunner: "jest-runner",// The paths to modules that run some code to configure or set up the testing environment before each testsetupFiles: ["./setupFile.js"],// A list of paths to modules that run some code to configure or set up the testing framework before each testsetupFilesAfterEnv: ["./setupTestFramework.js"],// The number of seconds after which a test is considered as slow and reported as such in the resultsslowTestThreshold: 5,// A list of paths to snapshot serializer modules Jest should use for snapshot testingsnapshotSerializers: ["enzyme-to-json/serializer"],// The test environment that will be used for testingtestEnvironment: "jest-environment-node",// Options that will be passed to the testEnvironmenttestEnvironmentOptions: {userAgent: "node.js",},// Adds a location field to test resultstestLocationInResults: true,// The glob patterns Jest uses to detect test filestestMatch: ["**/__tests__/**/*.[jt]s?(x)","**/?(*.)+(spec|test).[tj]s?(x)"],// An array of regexp pattern strings that are matched against all test paths, matched tests are skippedtestPathIgnorePatterns: ["/node_modules/","/dist/"],// The regexp pattern or array of patterns that Jest uses to detect test filestestRegex: [],// This option allows the use of a custom results processortestResultsProcessor: "jest-sonar-reporter",// This option allows use of a custom test runnertestRunner: "jest-circus/runner",// A map from regular expressions to paths to transformerstransform: {"^.+\\.jsx?$": "babel-jest","^.+\\.tsx?$": "ts-jest",},// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformationtransformIgnorePatterns: ["/node_modules/","\\.pnp\\.[^\\/]+$"],// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for themunmockedModulePathPatterns: ["/node_modules/react/"],// Indicates whether each individual test should be reported during the runverbose: true,// An array of regexp patterns that are matched against all source file paths before re-running tests in watch modewatchPathIgnorePatterns: ["<rootDir>/node_modules/"],// Whether to use watchman for file crawlingwatchman: true,};module.exports=config;