JavaScript Standard Style does not recognize jest - javascript

I need to setup jest and JavaScript Standard Style to work together when using npm test.
Now when I am running npm test the test fails because JavaScript Standard Style thrown an errors:
'test' is not defined.
'expect' is not defined.
I can work around this issue by defining in my package.json file some global for jest.
"standard": {
"globals": [
"fetch",
"test",
"expect"
]
}
But definitely I do not think it is a good solution.
In my test case sum.test.js
const sum = require('./sum')
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3)
})
In my package.json :
"scripts": {
"test": "standard && jest",
}
Question:
How to configure JavaScript Standard Style so it does not thrown an error when used with jest?

I was able to find a solution.
In package.json
"standard": {
"env": [ "jest" ]
}
Or in the test case:
/* eslint-env mocha */

In your .eslintrc.js file, include the following setting and you'll be good to go.
"env": {
"node": true,
"jest": true
}
If you are using a .eslintrc or a .eslintrc.json file, please use appropriate syntax.

Related

ava + ts-node converting .spec.ts files into .ts

I am running ava with ts-node with the following config:
"ava": {
"files": [
"tests/**/*",
"!test/exclude-files-in-this-directory",
"!**/exclude-files-with-this-name.*"
],
"failFast": true,
"failWithoutAssertions": false,
"extensions": [
"spec.ts",
"ts"
],
"environmentVariables": {
"NODE_ENV": "test"
},
"require": [
"ts-node/register",
"tsconfig-paths/register"
],
"tap": false,
"verbose": true
}
The problem is that .spec.ts files don't get recognized, as ts-node is doing some kind of conversion (I think) of the .spec.ts files into just .ts, which means that the extension with spec.ts is never matched.
Here's the output of the tests
- graphql › stage-2 › workspace.ts › do later
✔ general › functions.ts › returns proper difference
The files are named workspace.spec.ts and functions.spec.ts
Is there anyway for ts-node to not drop the spec part?
ts-node should only kick in when AVA requires the test file. I can't immediately spot why this isn't working. Are those spec.ts files inside the tests directory?
P.S. NODE_ENV already defaults to test, and you don't need to disable tap either.

jest says cannot import outside a module

I'm attempting make a few functions using the Test Driven Development (TDD)
I am writing in javascript.
checkTransparency(urlString)
maketransparent(urlString)
are two functions of mine I'm trying to test and develop which is located in a file called transcript.js.
These uses the inkscape and graphicsmagick npm. I checked checkTransparent works in some other project of mine, but I'm trying to make sure I can just copy paste this transparent.js into another project and use it elsewhere as well.
My folder structure of the project are the following :
+ node_modules
+ src
--- transparent.js
+ test
--- transparent.spec.js
+ package.json
+ package-lock.json
+ jest.config.js
I am using jest as my test framework.
The problem is when I run jest (or npm test)
I get the following:
FAIL test/transparent.spec.js
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
\\..............\transparent\test\transparent.spec.js:4 <FEW DETAILS OMITTED HERE DELIBERATELY>
import { checkTransparency, makeTransparent } from "../src/transparent"; // const transparent = require("../src/transparent");
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime._execModule (C:/Users/Kjeong/AppData/Local/Yarn/Data/global/node_modules/jest-runtime/build/index.js:988:58)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.862s
Ran all test suites.
my jest.config.js:
module.exports = {
testEnvironment: "node",
moduleDirectories: ["node_modules", "src", "transparent"],
moduleFileExtensions: [
"js",
"json",
"jsx",
"ts",
"tsx",
"node"
],
clearMocks: true,
}
I've tried the following exports to get this thing working:
export function checkTransparency(urlString) { ... }
export function makeTransparent(urlString) {... }
module.exports = {
checkTransparency: checkTransparency,
makeTransparent: makeTransparent,
};
In your package.json, using configuration like following could solve your problem:
{
"name": "<blah blah>",
"version": "1.0.0",
"description": "",
"type": "module",
"scripts": {
"start": "node server.js",
"test": "node --experimental-vm-modules node_modules/.bin/jest"
},
}
If you really want to use import keyword then you probably need to follow these explanations. Otherwise why not just require ?
const { checkTransparency, makeTransparent } = require('../src/transparent')
Hope this helps :)

Option "setupTestFrameworkScriptFile" was replaced by configuration "setupFilesAfterEnv", which supports multiple paths

Option "setupTestFrameworkScriptFile" was replaced by configuration "setupFilesAfterEnv", which supports multiple paths.
Please update your configuration.
I found this exact question here: setupTestFrameworkScriptFile is not supported error
I renamed my jest.config.js to setUpTests.js however that did not remove the deprecated error warning.
import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
configure({ adapter: new Adapter() })
package.json scripts
"scripts": {
"dev": "next -p 7777",
"build": "next build",
"start": "next -p 7777",
"test": "NODE_ENV=test jest --watch --no-cache",
"test-win": "SET NODE_ENV=test&& jest --watch"
}
"#types/enzyme": "^3.1.15",
"#types/jest": "^23.3.13",
"jest": "^24.1.0"
Jest used to have a config option called setupTestFrameworkScriptFile...
...but it was deprecated in favor of the newer setupFilesAfterEnv in PR #7119 which shipped with version 24.0.0.
Since you are using Jest ^v24.1.0 you will need to use setupFilesAfterEnv.
Just find where setupTestFrameworkScriptFile is used in your Jest config, rename it to setupFilesAfterEnv, and put the single file it used to point to in an array and you should be good to go.
Example, change this jest.config.js:
module.exports = {
...
setupTestFrameworkScriptFile: './setup.js',
...
}
...to this:
module.exports = {
...
setupFilesAfterEnv: ['./setup.js'],
...
}
If you are using create-react-app, change the key name at package.json file
from
"jest": {
// ...
"setupTestFrameworkScriptFile": "<rootDir>/src/setupTests.js",
to
"jest": {
// ...
"setupFilesAfterEnv": ["<rootDir>/src/setupTests.js"],
After I changed my file name from setupTests.js to setup.tests.js it worked. Maybe the dir path name did not match. Make sure you check that!
In my case in 'jest.config.js' I had
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts']
correctly referencing 'setup-jest.ts' in <rootDir>.
After renaming the file itself and the reference to it from
setup-jest.ts
to
setupJest.js
the error message vanished. Weird. Seems as if the hyphen in the file-name or being the same as in 'node_modules.jest-reset-angular.setup-jest.js' was the culprit.
Using Angular 13 and Jest (in package.json):
"jest": "^28.1.0",
"jest-preset-angular": "^12.1.0",
I'm on Lubuntu 22.04.
Jest message is not mantained anymore: https://github.com/mattphillips/jest-expect-message/issues
So I suggest using:
const msg = '... my message...'
expect({msg, result}).toEqual({msg, result: expected})
From https://github.com/facebook/jest/issues/3293
Or alternatively
function expectToBeTrue(result: any, message: string){
return expect({message, result}).toBe({message, result: true})
}
expectToBeTrue(compute() == 1, "Oh no compute should return 1!")

How to configure StandardJS?

One of the main features of StandardJS is that it doesn't require configuration.
The problem is that I want to configure it. I don't want to put:
/* eslint-env mocha */
...in every test file. I want to configure StandardJS to treat everything in the test directory as mocha tests.
I've found in the README that some configuration is possible, e.g.:
{
"standard": {
"globals": [ "myVar1", "myVar2" ]
}
}
...but I'm struggling to find more comprehensive documentation about the configuration options. Is it possible to configure StandardJS to treat files in different directories differently?
You have a couple of options to try out and see what works for your specific project depending on the recent implementation of StandardJS.
Define your own globals
in package.json:
"standard": {
"globals": [
"describe",
"before",
"after",
"beforeEach",
"afterEach",
"it",
"assert"
]
}
or in .eslintrc:
{
"globals": {
"describe": false,
"before": false,
"after": false,
"beforeEach": false,
"afterEach": false,
"it": false,
"assert": false
}
}
More on ESLint's configuration.
Define an environment
in package.json:
"standard": {
"env": {
"mocha": true
}
}
or in .eslintrc:
{
"env": {
"mocha": true
}
}
Check out currently available environments
Run StandardJS as an NPM script with the environment specified
in package.json:
{
"scripts": {
"lint": "standard --env mocha"
}
}
Use a plugin
after installing the plugin (e.g. eslint-plugin-mocha)
in package.json:
"standard": {
"plugins": [
"mocha"
]
}
or in .eslintrc:
{
"plugins": [
"mocha"
]
}
Create your own, customized rules based on StandardJS
Check out this repository. The quick rundown:
Install with:
npm install --save-dev eslint-config-standard eslint-plugin-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node
Then create a .eslintrc file by extending StandardJS and start to fill with your own rules:
{
"extends": "standard"
}
Since StandardJS uses ESLint under the hood, you can pretty much configure it however you want it using ESLint's documentation.

How do I move jest tests to a /test folder and get them to run?

edit: I'm pretty sure this question is out of date and Jest has changed since then. Don't assume the answers will work or even be relevant now.
Jest expects tests to be in _tests_ folder or to be named blah.test.js. I don't like either of those patterns. I want my test files to be in /test and naming them test/index.ios.test.js seems redundant and silly. My first stab at this is to change my jest config in package.json to be:
"jest": {
"testPathDirs": ["test"],
"testRegex": "\\.(js|jsx)$",
"preset": "react-native"
}
Which find the tests successfully but they all fail:
Cannot find module 'setupDevtools' from 'setup.js'
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:151:17)
at Object.<anonymous> (node_modules/react-native/jest/setup.js:23:1)
That function is in node_modules/react-native/Libraries/Core/Devtools/setupDevtools.js. How do I tell Jest where to find it?
I solved the problem by just setting the regex so it finds all .js files in my ./test folder:
"jest": {
"preset": "react-native",
"globals": {
"__DEV__": true
},
"testRegex": "./test/.*.js$",
"rootDir": "."
},
(jcollum here: I don't know what __DEV__ is actually doing there but an error will be thrown if isn't. jest 17.0.3)
I think the best way to go about this is to configure testMatch. It defaults to:
[ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ]
So you could either change __tests__ to tests or add a new entry into the array that checks for both. My use the following in my package.json:
"jest": {
"testMatch": [ "**/tests/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ]
},
I think to set roots: ['<rootDir>/test/'] is simple way in jest.config.js
module.exports = {
roots: ['<rootDir>/test_unit/'],
...
}
It works well for me.

Categories

Resources