I am having difficulties running my jest tests from stackblitz.
I have configured a start command in .stackblitzrc but my tests are not run...
My jest config is as follows:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$',
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
setupFilesAfterEnv: ['#testing-library/jest-dom', 'src/setupTests.ts'],
};
Here is the stackblitz:
https://stackblitz.com/edit/react-74twff
Can someone please help?
First, the template you started out with doesn't look like it supports Web Containers. I'm not sure if there's a way to migrate it or not. In order to use Web Containers, you start with a Node-based template and add functionality to that.
Below is a sample I put together that should get you working. You should be able to fork this and add your application's files or use it as a reference when building a new Stackblitz project.
https://stackblitz.com/edit/webpack-5-react-starter-ahpjpn?file=src/app.test.tsx
I am new this framework. I connected PostgreSQL database using ormconfig file. but I need to configure development environment, production environment, test environment. How to achieve this scenarios. I tried to use config service in my project. but always connected only .env file configuration.
development.env
POSTGRES_HOST=127.0.0.1
POSTGRES_PORT="5432"
POSTGRES_USER=postgres
POSTGRES_PASSWORD='*****'
POSTGRES_DATABASE=testdb123
PORT=4000
You could use ormconfig.js and at the top of it add something like this:
require('dotenv').config({
path: '.env.' + process.env.NODE_ENV
})
Another option is to import ConfigModule like this:
ConfigModule.forRoot({
load: [config],
envFilePath: '.env.' + process.env.NODE_ENV
})
And use async configuration for TypeORM:
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
type: 'mysql',
host: configService.get('POSTGRES_HOST'),
port: +configService.get<number>('POSTGRES_PORT'),
username: configService.get('POSTGRES_USER'),
password: configService.get('POSTGRES_PASSWORD'),
database: configService.get('POSTGRES_DATABASE'),
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: configService.get('TYPEORM_SYNC'),
}),
inject: [ConfigService],
})
I use a similar async configuration here.
Well, I would recomment to keep .env file under git ignore and have a .env.example with all possible configuration items.
If you like to have a default settings for every env, you can use something like
https://www.npmjs.com/package/dotenv-defaults
If you want to use DI & typing as well as env files for each environments, take a look at the nest configuration module
I am using NEST.JS framework and want to add external plugin New Relic Apollo Server plugin.
apollo-server-fastify: "^2.19.2"
#newrelic/apollo-server-plugin: "^0.1.2"
import { apolloServerNewRelicPlugin } from '#newrelic/apollo-server-plugin';
GraphQLModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
....
plugins: [apolloServerNewRelicPlugin],
}),
When I start server for e2e test it required real NewRelic key ; is there a way to start for test environment without requiring real key ?
To test out things I started server with real key; Missing Key and cannot start agent error disappeared but below is the error I am seeing
UnhandledPromiseRejectionWarning: TypeError: Cannot use 'in' operator to search for '__internal_plugin_id__' in undefined
my-application | at Object.pluginIsInternal (/usr/src/app/node_modules/apollo-server-fastify/node_modules/apollo-server-core/dist/plugin/internalPlugin.js:5:37)
Update: the plugin has been updated and it supports TypeScript now.
I've had the same error initially. The way I made it work here was to create a typings/newrelic-apollo-server-plugin/index.ts file containing a module declaration:
declare module '#newrelic/apollo-server-plugin'
Then, in my NestJS module file:
import apolloServerNewRelicPlugin from '#newrelic/apollo-server-plugin'
#Module({
imports: [
...
GraphQLModule.forRoot({
...
plugins: [apolloServerNewRelicPlugin],
}),
I am using Nest.js+TypeORM to develop and try to deploy in my computer.
I can connect to mysql in develop mode, but it failed in product mode.
Below is my TypeORM config.
#Module({
imports: [
AuthModule,
ClassificationModule,
ArticleModule,
UserModule,
CommentModule,
FragmentModule,
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
// logging: ["query"],
port: 3306,
username: 'root',
password: '123456',
database: 'myblog',
entities: ['src/**/**.entity{.ts,.js}'],
synchronize: true
})
]
})
export class AppModule { }
In develop mode, it can connect to mysql successfully.
But in product mode, it shows can't connect mysql.
ts-node manages your typescript compilation in memory and handles chaning references from src to dist internally. However, this is a problem when you get into running your pure node variant, as you'll be in a dist directory instead of src, so TypeORM won't be able to find your entities with the defined entities array. Instead you should use entities: [join(__dirname, '/**/*.entity.{js,ts}')], to allow for dynamically changing between ts and js so you don't have to worry about what you are running with.
I would also suggest using tsc-watch for develpoment, as it will run node by default on successful compilation and you won't have to worry about memory consumption from ts-node.
Every time I run jest it never runs anything. I have let the counter go arbitrarily high. I have run jest with --no-cache
jest --debug output is as follows:
{
"configs": [
{
"automock": false,
"browser": false,
"cache": true,
"cacheDirectory": "/var/folders/7v/64n1tsk11zs2pbwf5bm_c9kc0000gn/T/jest_dx",
"clearMocks": false,
"coveragePathIgnorePatterns": [
"/node_modules/"
],
"detectLeaks": false,
"forceCoverageMatch": [],
"globals": {},
"haste": {
"defaultPlatform": "ios",
"platforms": [
"android",
"ios",
"native"
],
"providesModuleNodeModules": [
"react-native"
]
},
"moduleDirectories": [
"node_modules"
],
"moduleFileExtensions": [
"js",
"json",
"jsx",
"node"
],
"moduleNameMapper": [
[
"^React$",
"/Users/skilurus/github/flock-react-app/node_modules/react"
]
],
"modulePathIgnorePatterns": [
"/Users/skilurus/github/flock-react-app/node_modules/react-native/Libraries/react-native/"
],
"name": "b29a126b130a0be47202d3bc7b00f1b4",
"resetMocks": false,
"resetModules": false,
"restoreMocks": false,
"rootDir": "/Users/skilurus/github/flock-react-app",
"roots": [
"/Users/skilurus/github/flock-react-app"
],
"runner": "jest-runner",
"setupFiles": [
"/Users/skilurus/github/flock-react-app/node_modules/regenerator-runtime/runtime.js",
"/Users/skilurus/github/flock-react-app/node_modules/react-native/jest/setup.js",
"/Users/skilurus/github/flock-react-app/test-setup.js"
],
"snapshotSerializers": [
"/Users/skilurus/github/flock-react-app/node_modules/enzyme-to-json/serializer.js"
],
"testEnvironment": "/Users/skilurus/github/flock-react-app/node_modules/jest-environment-jsdom/build/index.js",
"testEnvironmentOptions": {},
"testLocationInResults": false,
"testMatch": [
"**/__tests__/**/*.js?(x)",
"**/?(*.)(spec|test).js?(x)"
],
"testPathIgnorePatterns": [
"/node_modules/",
"e2e"
],
"testRegex": "",
"testRunner": "/Users/skilurus/github/flock-react-app/node_modules/jest-jasmine2/build/index.js",
"testURL": "about:blank",
"timers": "real",
"transform": [
[
"^.+\\.js$",
"/Users/skilurus/github/flock-react-app/node_modules/babel-jest/build/index.js"
],
[
"^[./a-zA-Z0-9$_-]+\\.(bmp|gif|jpg|jpeg|mp4|png|psd|svg|webp)$",
"/Users/skilurus/github/flock-react-app/node_modules/react-native/jest/assetFileTransformer.js"
]
],
"transformIgnorePatterns": [
"node_modules/(?!react-native|native-base|react-navigation|react-native-fabric|tipsi-stripe)"
],
"watchPathIgnorePatterns": []
}
],
"globalConfig": {
"bail": false,
"changedFilesWithAncestor": false,
"collectCoverageFrom": [
"src/**/*.{js,jsx}"
],
"coverageDirectory": "/Users/skilurus/github/flock-react-app/__coverage__",
"coverageReporters": [
"json",
"lcov",
"text"
],
"coverageThreshold": {
"global": {
"branches": 70,
"functions": 75,
"lines": 85,
"statements": 80
}
},
"detectLeaks": false,
"expand": false,
"globalSetup": null,
"globalTeardown": null,
"listTests": false,
"mapCoverage": false,
"maxWorkers": 7,
"noStackTrace": false,
"nonFlagArgs": [],
"notify": false,
"notifyMode": "always",
"passWithNoTests": false,
"rootDir": "/Users/skilurus/github/flock-react-app",
"runTestsByPath": false,
"testFailureExitCode": 1,
"testPathPattern": "",
"testResultsProcessor": null,
"updateSnapshot": "new",
"useStderr": false,
"verbose": true,
"watch": false,
"watchman": true
},
"version": "22.3.0"
}
node --version: 8.9.4
npm --version: 5.6.0
yarn --version 1.3.2
Has anybody seen anything similiar? Does anybody know hot to fix this?
This happens to me too but it's intermittent, very frustrating though. I have discovered a workaround which is to run using the --runInBand flag, which just runs tests in the same thread:
jest --runInBand
Run you tests like so:
jest --detectOpenHandles --forceExit
--detectOpenHandles logs out errors preventing your tests from exiting clearly and it implies --runInBand which ensures your tests run in the same threads so no overlapping.
--forceExit which terminates your tests if something is wrong instead of hanging.
For the record, in my case it turned out to be a caching problem (I tried many many other things before).
For jest >=22.0.0 use the --clearCache option to clear the cache.
For jest <22.0.0 use the --showConfig option, search for the cacheDirectory property and delete the mentioned directory.
Hope this helps someone.
On MacOS uninstalling and reinstalling watchman didn't work for me.
Running watchman version hangs indefinitely.
do this to fix the watchman from hanging:
launchctl unload ~/Library/LaunchAgents/com.github.facebook.watchman.plist
watchman version
https://github.com/facebook/watchman/issues/381#issuecomment-257673900
You should see something like this then you know it worked:
{
"version": "2021.08.23.00"
}
Then re-run your jest tests
On MacOS I fixed this by uninstalling and reinstalling watchman using brew uninstall watchman and then reinstalling with brew install watchman. I had recently upgraded the OS so that may have something to do with it.
I had a similar issue. Most of my test where running but one suite was continuously running and never erroring.
It turned out I had a race condition in one of my useEffects. Which just cause jest to continuously run.
To diagnose the issue:
Comment out all test but one. keep adding a test till you find the one triggering the error.
Analyze the test to Identify which code is effected. (My issue turned out to be in a UseEffect.)
Identify which state object is causing the race condition.
Fix: remove it or throw a condition check on your code to prevent the race condition
In my case it was because I was using a jest plugin for VS code and auto save was enabled. So, jest hanged after running too many times.
Removing the /tmp/jest_rs solved my problem.
So I had a situation similar to this, only that jest refused to run any of my tests! The cause was a little convoluted:
I hadn't run the project in over 6 months and various dependencies had picked up vulnerability issues.
Back when I had last run the project and tests, I had jest installed globally with a global config.
Then at one point, I had uninstalled jest from global (hence losing the global config) but didn't remember to add a local one to the project I'm talking about.
When debugging to try and get the tests to run, I nuked my node modules and did a fresh install.
Only after adding a jest.config with setting the no cache options did it eventually work out.
In summary:
If you don't have jest installed globally, make sure to have a jest config for your project.
After using the cli to set up the config, go back and manually check all the options you've chosen are there and modify the ones cli didn't prompt for.
I had the same issue, tests pass and then it hangs and the CI hangs too. I stumbled upon --forceExit, and it fixed it for me.
Debug useEffect hook used inside components because some times useEffect creates infinite loop problems and the jest doesn't finishes the tests
I have fixed this by modifying my .babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
[
"styled-jsx/babel",
{
// "plugins": ["styled-jsx-plugin-postcss"]
}
]
]
}
In my case I tried everything around internet and the only solution was to set isolatedModules: true (I explicitly set it to false).
In my case, updating nodejs from an older version (ie. 12.16.1) to something more recent (eg. 14.17.3) and then re-installing jest (npm install jest -g) resolved this completely.
I had something similar with the project on NestJS. It turned out that one of the modules contained an imported module, but it was not installed. And for some inexplicable reason, there was no information about this when the tests were launched.
check your tests, in my case I mistake and put an extra "a" on the test
test('test expected that ..', async (a) => {
...
this makes my test hang forever (using node 14.15 and jest 29.1.2).
The #rohit's answer has given me the clue to find the solution to my problem, my code was working fine, but jest was failing into an infinite loop with the useEffect
so I've solved making a mock of it
import React from 'react'
const mockUseEffect = jest.fn()
jest.spyOn(React, 'useEffect').mockImplementation(mockUseEffect)
you can adapt it as your needs