Vite allows to import files as raw strings using
import foo from "foo.txt?raw"
However, jest complains that it cannot find the file. I found the jest-raw-loader, but I don't know how to tell it to apply raw loading to the "?raw" syntax.
I added the following to moduleNameMapper it worked.
"moduleNameMapper": {
".*\\.txt\\?raw": "jest-raw-loader"
}
Related
I have some helper functions inside the /src/common/helper/cash.helper.ts. When I call this function from a module, I get the following error.
Error: Cannot find module './../../../src/common/helper/cast.helper' Require stack:
However, the e2e tests are working without any problem. Here, you can see the folder structure.
When I change the import to absolute path import { toNumber } from 'src/common/helper/cast.helper'; It's working, but the e2e tests are not working.
What's wrong here? How can I use common functions and constants across all the modules in NestJS?
I did the following to fix the issue.
I changed the import to absolute path import { toNumber } from 'src/common/helper/cast.helper';
To fix the e2e test, I have added "moduleDirectories": ["<rootDir>/../", "node_modules"] to the jest-e2e.json.
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!
I try to implement e2e tests in a simple NestJS project (generate with 'nest new' command, add some dependencies and config Project here), the existing tests (not e2e ones) run properly (all modules are resolved).
But, when I execute the default app.e2e-spec.ts (generated by nest cli), I got this following error
Cannot find module 'cls-hooked' from 'src/common/http-context.ts'
The only difference between working and broke version is the test file selected (in the jest config)
testRegex: '.e2e-spec.ts$', // Doesn't work
// testRegex: '.*\\.spec\\.ts$', // Work
The module resolution with TS works well when I look for the trace of tsc --traceResolution
The project is running correctly and works well. Then, globally, Jest & TS are well configured
The error is the same when I use a relative path
// src/common/http-context.ts
// import * as cls from 'cls-hooked';
import * as cls from '../../node_modules/#types/cls-hooked';
When I explicitly set the path to module
moduleNameMapper: {
'cls-hooked': '<rootDir>/node_modules/#types/cls-hooked/index.d.ts',
},
The error suggest an interoperability issue
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:
C:\Users\taquet_p\Sources\nestJsGrapQLTest\test-jest-imports\node_modules\#types\cls-hooked\index.d.ts:8
import { EventEmitter } from 'events';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import * as cls from 'cls-hooked';
| ^
2 |
3 | export class HttpContext {
4 |
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (src/common/http-context.ts:1:1)
I tried to configure support for ECMAScript module and other things in tsconfig.json and jest.config.js
I check most of SOF questions about Cannot find module within Jest
I have no more ideas to googling about.
Do anyone has a solution ? A suggestion ?
The github repo provide the atomic project to reproduce the issue directly. Just pull, npm install & run test (the jest config file is a bit dirty :-) )
I am using create-react-app. Running jest from the CLI causes this error (though in VS Code it shows in my test file that my test passes):
(base) ➜ component-library git:(setup) ✗ jest
FAIL src/App.test.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:
• 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:
/Users/Me/go/src/gitlab.com/tensile-payments/component-library/src/setupTests.js:5
import '#testing-library/jest-dom';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
My setupTests.js file looks like this:
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '#testing-library/jest-dom';
import Enzyme from 'enzyme';
import Adapter from '#wojtekmaj/enzyme-adapter-react-17';
Enzyme.configure({ adapter: new Adapter() });
I understand from another question's answer that Jest Babel-transforms files before running tests, which should get rid of these import statements. I haven't ejected and so haven't changed the babel config. Other people had the issue that node modules weren't being transformed because the default config excludes them, but this error isn't coming from a node module. How can I fix this?
I fixed it by running tests with npm run test instead of jest, as well as removing
"jest": {
"setupFilesAfterEnv": [
"<rootDir>src/setupTests.js"
]
}
from my package.json (though Enzyme instructs to include it when using Jest).
I'm developing an application with Adonis v5 but its test runner isn't finished. So, my workaround is to apply Jest in its place. I got this working but I'm having trouble importing types from Adonis.
In any model, I have the following import:
import { BaseModel, column } from '#ioc:Adonis/Lucid/Orm'
To solve the alias, I added this rule in jest.config.js:
moduleNameMapper: {
'^App(.*)$': '<rootDir>/app$1',
'^#ioc:Adonis/Lucid/Database$': '#adonisjs/lucid/build/src/Database/index.js',
'^#ioc:Adonis/Lucid/Orm$': '#adonisjs/lucid/build/adonis-typings/orm.d.ts',
//'^#ioc:Adonis/Core/Validator$': '',
},
The third rule points to the previous import. Inside of the pointed file, I found the declaration of a module which exports the desired types.
declare module '#ioc:Adonis/Lucid/Orm' {
import { ScopeFn, LucidModel, HooksDecorator, ...
...
The complete file is this.
When I run Jest, I get this error. What am I missing? Before I forget, I'm using ts-jest to define the settings of Jest.