how to run a file with .cjs extension in Jest - jestjs

I am having an issue with running a .cjs file with jest. jest --path/to/my/file/sometest.test.cjs is not finding that file.Also "testMatch":["**/?(*.)+(spec|test).cjs"] is giving testMatch: **/?(*.)+(spec|test).cjs - 0 matches. Any advise?

Related

Mock zip.js lib to be able to use jest

So, I have a project that imports a package utils, and this package depends on '#zip.js/zip.js' lib. This lib is meant for browser usage and doesn't work on node.
The first weird thing is that, when I try to run jest, I get:
FAIL tests/index.test.ts
● 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:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• 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:
./node_modules/#zip.js/zip.js/index.js:29
import Deflate from "./lib/core/codecs/deflate.js";
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import {
| ^
2 | Data64URIWriter,
3 | Entry,
4 | TextWriter,
at Runtime.createScriptFromCode (../../node_modules/jest-cli/node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (../utils/src/unzipFolder.ts:1:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 5.926 s
Which is totally misleading.
Anyway, now that I know that the problem is the usage of zip.js on node, I need to mock it so that jest doesn't break.
According to the docs for Manual mocks, here is what I did:
create a folder __mocks__ in the root folder (next to node_modules)
create a folder #zip.js inside it
create a file zip.js inside
It didn't work. So I tried the code we see in that doc and try to add jest.mock('#zip.js/zip.js') as first line in my test file, but to no avail.
I'm really not sure about how the mock system is actually working, so any help is really appreciated.
Edit:
I'll keep here the list of what was tried and failed:
using "type": "module" in package.json (same result)
All solutions from here and there (same result. Anyway, I'm convinced that the error message is just misleading)
I discovered the moduleNameMapper feature from jest. It totally solved my problem.
Here is my final jest.config.js file:
export default {
preset: 'ts-jest',
testEnvironment: 'node',
moduleNameMapper: {
'#zip.js/zip.js': '<rootDir>/__mocks__/#zip.js/zip.js',
},
}
And here is what I have in <rootDir>/__mocks__/#zip.js/zip.js file:
module.exports = {}
Hope it helps someone!

Jest.config settings modulePathIgnorePatterns and testPathIgnorePatterns aren't having any effect

I'm running tests in a node app using jest. I can get tests running properly, but I can't seem to tell jest to ignore directories. For example, when I try to test a specific file convertExistingImages.ts with the command: npm test convertExistingImages I get a response in my terminal of:
> mfa-bot-2022#1.0.0 test
> jest
FAIL dist/utils/maintenance.ts/convertExistingImages.test.js
● Test suite failed to run
Your test suite must contain at least one test.
(...)
FAIL src/utils/maintenance/convertExistingImages.test.ts
● Test suite failed to run
(...)
As you can see, a duplicate file in my /dist folder is also being tested, which I don't want.
I've tried updating my jest.config.ts file as follows:
module.exports = {
"preset": "#shelf/jest-mongodb",
"modulePathIgnorePatterns": ["/build/"],
"testPathIgnorePatterns": ["/node_modules/", "/build/"]
}
But the modulePathIgnorePatterns and testPathIgnorePatterns settings aren't having any effect.
Can anyone tell me what I'm doing wrong?
You configured it to ignore the build folder but your conflict is in the dist folder. Change build to dist in your ignore settings.
You can read more about this config on the Jest site here.

Jest: Automatically collect coverage from tested files

In my application, while developing, I run:
npm run test src/components/component.test.tsx
This runs the specific test suite for the component I'm working on.
On top of that, I can then change it to:
npm run test src/components/component.test.tsx -- --coverage --coverageReporters=text-summary --collectCoverageFrom=src/components/component.tsx
Which will print a coverage report for that specific file once the tests have been run.
As you can see this is extremely wordy and only gets worse if I want to test two or three files at the same time.
Is there any way to automate collectCoverageFrom to collect coverage from the files that have been tested (not from all files in the project) so that I don't have to type it out manually every single time?
Just omit the "collectCoverageFrom" (or explicitly set it to an empty glob if you're overriding the config file).
Jest will then only collect coverage from files that are used during the test run.
Set it up in your jest configuration file.
your npm script will look like jest -c path/to/jest.config.js
jest.config.js will look like
module.exports = {
collectCoverage: true,
// The directory where Jest should output its coverage files
coverageDirectory: "./coverage",
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
coverageReporters: ["html", "text", "cobertura"],
}
If you do jest --init it will help you build a new config file
Side note: You may want to set up a jest wildcard so you don't need to individually write down every file you want to test.

Jest regex to match certain test files

I have integration tests under dir src/test/integration. All files are named like so: foo.integration.js.
Running Jest:
jest ".*\\.integration\\.js"
produces this error:
No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
In /Users/dangruszczyk/workspace/cef/lambda-workflow
7 files checked.
testMatch: **/__tests__/**/*.[jt]s?(x), **/?(*.)+(spec|test).[tj]s?(x) - 1 match
testPathIgnorePatterns: /node_modules/ - 7 matches
testRegex: - 0 matches
Pattern: .*\.integration\.js - 0 matches
Surely this regex should match src/test/integration/foo.integration.js (https://regex101.com/r/T3WJwd/1/). Any clue why it does not?
The problem is that Jest is still applying the testMatch, i.e. you're filtering within the files it has already determined to be test files, and src/test/integration/foo.integration.js matches neither **/__tests__/**/*.[jt]s?(x) nor **/?(*.)+(spec|test).[tj]s?(x)*.
To run those files, you're probably best off setting the testMatch instead:
jest --testMatch='**/*.integration.js'
This doesn't seem to be a documented part of the CLI, but works fine (for now!) in practice.
* Interestingly, neither does path/to/my-test.js, the example shown in the docs...
I was doing the same thing, but in the end it felt more natural to restructure.
By using .test.js you can easily run all tests or selectively filter sub-types.
example.integration.test.js
example.unit.test.js
"scripts": {
"test-all": "jest",
"unit-test": "jest \"--testPathPattern='.+\\.unit\\.test\\.js$'\"",
"integration-test": "jest \"--testPathPattern='.+\\.integration\\.test\\.js$'\""
},
As others have said, jest expects test files to end .test.js or .spec.js.

Jest ignore Cypress test

I have a create-react-app app and used to use jest for testing but I'm slowly migrating to cypress.
The thing is, now when I run my jest tests, it includes my cypress tests and gives an error
ReferenceError: Cypress is not defined
How can I make it that my jest (naming convention *.test.js) test ignore my cypress test (which are usually called *.spec.js)?
You should use testPathIgnorePatterns in your jest config.
An array of regexp pattern strings that are matched against all test paths before executing the test. If the test path matches any of the patterns, it will be skipped.
According to Jest config docs
jest.config.js
module.exports = {
// Your normal jest config settings
testPathIgnorePatterns: ["<rootDir>/cypress/"],
}
In your jest/config.js or wherever you have your jest config (could be package), add the following to replace the default regex to find tests from
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$"
to:
"testRegex": "(/__tests__/.*|(\\.|/)(test))\\.[jt]sx?$"

Resources