How to allow ts-jest to compile with errors - javascript

First time writing tests in typescript for my expo project. I've got some errors in my Typescript (the actual typing), but the functionality works. When I run my tests, ts-jest doesnt allow the tests to run since the types are incorrect (even though the functionality works). Is there some setting to allow ts-jest to run regardless of type errors?
App.test.tsx
import React from "react";
import renderer from "react-test-renderer";
import SignUp from "../screens/Auth/screens/SignUp";
describe("<App />", () => {
it("has 1 child", () => {
const tree = renderer.create(<SignUp />).toJSON();
console.log(tree);
});
});
jest.config.js
const { defaults: tsjPreset } = require("ts-jest/presets");
/** #type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "react-native",
transform: {
"^.+\\.jsx$": "babel-jest",
"^.+\\.tsx?$": [
"ts-jest",
{
tsconfig: "tsconfig.spec.json",
},
],
},
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
};
babel.config.js
/** #type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
}

Related

Next.js + Jest moduleNameMapper without TypeScript

I am struggling to get moduleNameMapper to work with NextJS / JavaScript. For this project we are not using TypeScript.
Next: 12.2.5
React: 18.2.0
Jest: 29.0.1
Jest environment jsdom: 29.0.1
Here is my jsconfig.json file
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#/components/*" : ["components/*"],
"#/styles/*" : ["styles/*"],
"#/config/*" : ["config/*"],
"#/hooks/*" : ["hooks/*"],
"#/store/*" : ["store/*"],
}
}
}
I can do the following in my project
import Layout from "#/components/Layout"
import useFetch from "#/hooks/fetch"
However, when I try to test I get this message
Cannot find module #/hooks/fetch from pages/account/login/index.js
Here is my jest.config.js file
const nextJest = require('next/jest');
const createJestConfig = nextJest({
dir: "./",
});
const customJestConfig = {
moduleDirectories: ["node_modules", "<rootDir>"],
moduleNameMapper: {
"^#/hooks/*": "/hooks/*"
},
testEnvironment: "jest-environment-jsdom",
}
module.exports = createJestConfig(customJestConfig)
As you can see I am trying to map the paths in moduleNameMapper but this still isn't working. How do I correct this?
I am hoping to use the same import formatting for both project and test project
many thanks
Managed to resolve this by changing the jsconfig.js file
const nextJest = require('next/jest');
const customJestConfig = {
moduleDirectories: ["node_modules", "<rootDir>"],
testEnvironment: "jest-environment-jsdom",
};
const createJestConfig = nextJest({
dir: './',
})(customJestConfig);
module.exports = async () =>
{
// Create Next.js jest configuration presets
const jestConfig = await createJestConfig();
// Custom `moduleNameMapper` configuration
const moduleNameMapper = {
...jestConfig.moduleNameMapper,
'^#/(.*)$': '<rootDir>/$1',
};
return { ...jestConfig, moduleNameMapper };
};
Source: https://github.com/vercel/next.js/issues/36682

ts-jest cannot resolve tsconfig aliases

I have a typescript project and I setup aliases in ts.config.json
{
"compilerOptions": {
"paths": {
"#pkg/*": ["./packages/*"],
},
}
}
in my ts files I can shorten my import paths
// example.ts
import {someThing} from '#pkg/mypackage'
it works fine with tsc and vscode can recognize the alias path correctly.
but when I run npm t whitch runs jest it fails
Cannot find module '#pkg/mypackage' from 'example.ts'
jest.config.js
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
transform: {
"^.+\\.tsx?$": "ts-jest",
},
};
I added this to my package.json file
"jest": {
"moduleNameMapper": {
"#pkg/(.*)": "<rootDir>/packages/$1"
}
}
I managed to use pathsToModuleNameMapper, but I had this issue
https://github.com/kulshekhar/ts-jest/issues/2709
I had the same problem, but managed to get it working by using a couple of plugins. I also have some extra matchers at the end for some additional test types.
My Jest-base.config.js has the tsconfig-paths-jest plugin installed and running. This plugin solved my tsconfig path issues.
I use a common base file for common configuration between unit tests and end to end tests, both of which I run via Jest currently.
jest-base.config.ts
const tsconfig = require('./tsconfig.json');
const moduleNameMapper = require('tsconfig-paths-jest')(tsconfig);
module.exports = {
moduleNameMapper,
preset: 'ts-jest',
testEnvironment: 'node',
rootDir: './',
collectCoverage: true,
collectCoverageFrom: [
'<rootDir>/**/*.ts',
'!<rootDir>/**/*.interface.ts',
'!<rootDir>/**/*.mock.ts',
'!<rootDir>/**/*.module.ts',
'!<rootDir>/**/__mock__/*',
'!<rootDir>/src/main.ts'
],
coverageProvider: 'v8',
coverageReporters: [
'clover',
'json',
'lcov',
'text',
'text-summary'
],
resetModules: true,
setupFiles: [
'dotenv/config'
],
// Add the community jest-extended matchers
setupFilesAfterEnv: [
'jest-extended'
],
verbose: false
};
My jest.config.js (for unit tests) will extend my jest-base.config.js to add unit test specific code such as coverage requirements, where to store output for coverage etc.
jest.config.js
const JestBaseConfiguration = require('./jest-base.config');
module.exports = Object.assign(JestBaseConfiguration, {
moduleFileExtensions: ['js', 'json', 'ts'],
testRegex: '.e2e-spec.ts$',
transform: {
'^.+\\.(t|j)s$': 'ts-jest'
},
...

TypeError: Cannot read property 'cwd' of undefined

I am writing test case using jest and react-testing-library
When i run my test script it throws an error as below
TypeError: Cannot read property 'cwd' of undefined
Now I have tried almost everything to solve this but did not find cause of this
I tried to change config , Even I have run using --no-cache but again it throws the
same error
here is my config file
const { defaults } = require("jest-config");
module.exports = {
testEnvironment: "node",
// setupFiles: [
// "<rootDir>/../apollo-server-env/dist/index.js"
// ],
preset: "ts-jest",
testMatch: null,
testRegex: ".*test*\\.(ts|tsx|js)$",
testPathIgnorePatterns: [
"/node_modules/",
"/dist/"
],
transform: {
"\\.(gql|graphql)$": "jest-transform-graphql",
"\\.(ts|tsx)$": "ts-jest",
// Use our custom transformer only for the *.js and *.jsx files
"\\.(js|jsx)?$": "./transform.js",
// future need to test with
// "^.+\\.(js|jsx|ts|tsx)$": "./transform.js",
// ".+\\.(css|styl|less|sass|scss)$": "jest-css-modules-transform"
},
roots: [
"packages",
"packages-modules",
"servers"
],
moduleFileExtensions: [...defaults.moduleFileExtensions,
"ts",
"tsx",
"js",
"gql",
"graphql"],
moduleNameMapper: {
'^__mocks__/(.*)$': '<rootDir>/../../__mocks__/$1',
// This regex should match the packages that we want compiled from source
// through `ts-jest`, as opposed to loaded from their output files in
// `dist`.
// We don't want to match `apollo-server-env` and
// `apollo-engine-reporting-protobuf`, because these don't depend on
// compilation but need to be initialized from as parto of `prepare`.
'^(?!apollo-server-env|apollo-engine-reporting-protobuf)(apollo-(?:server|datasource|cache-control|tracing|engine)[^/]*|graphql-extensions)(?:/dist)?((?:/.*)|$)': '<rootDir>/../../packages/$1/src$2'
},
transformIgnorePatterns: [
"/node_modules/(?!(#vscode)/).*/"
],
clearMocks: true,
globals: {
__BACKEND_URL__: 'http://localhost:3010',
__GRAPHQL_URL__: 'http://localhost:8085/graphql',
/*"ts-jest": {
tsConfig: "<rootDir>/tsconfig.json",
//https://github.com/kulshekhar/ts-jest/issues/766,
"diagnostics": {
"warnOnly": true
},
"babelConfig": true
}*/
}
};```
Here is my test file
`import * as React from 'react';
import {render, cleanup} from 'react-testing-library';
import {EditorComponent} from '../components/editor/editor-component';
import { Provider } from 'react-fela';
import { createRenderer } from 'fela';
import 'jest';
import 'jest-dom/extend-expect';
import { MockedProvider } from 'react-apollo/test-utils';
import {FILE_CONTENT_QUERY} from '../../../files-graphql-client/src/queries/index';
const mocks = [{
request: {
query : FILE_CONTENT_QUERY,
},
result: {
data: {
'getReleaseNotes': {},
},
},
}];
describe('<EditorComponent/>', () => {
let componentObj, felaRenderer, props = {
subscriber: jest.fn(),
saveDelayFileChangesMutation: jest.fn(),
loadFileContent: function () {
return new Promise(function(resolve) {
setTimeout(function() {
resolve({data: {loadFileContent: {
'loadFileContent': {},
}}});
}, 300);
});
},
openingFiles: [{
value : 'test',
encoding: 'utf-8',
oldValue : 'oldTest',
deleted : false,
addIgnore : 'test',
editorId : 1,
markdown: false,
preview : true,
preOpen : false,
keepOpen : true,
status : 'test',
oversize : false,
changed : true,
changedEvent: {},
diff : true,
size : 25,
}] as IContent[],
allSave: false,
rootPath: '',
change: jest.fn(),
actions: [],
doneSaveAll: jest.fn(),
changeEditorSubscribes: jest.fn(),
updateEditorContent: jest.fn(),
openDiffEditor: jest.fn(),
closeConflicts: jest.fn(),
closeEditor: jest.fn(),
updateChangedContent: jest.fn(),
setFinderOptions: jest.fn(),
onOpenFile: jest.fn(),
styles: {},
subscribeToMore: jest.fn(),
};
beforeEach(() => {
felaRenderer = createRenderer();
componentObj = render(<MockedProvider mocks={mocks}><Provider renderer={felaRenderer}><EditorComponent {...props}/></Provider></MockedProvider>);
});
afterEach(cleanup);
});`
Just install the older version of babel-jest: 22.
No need to change the version of jest, latest version can be used.
Latest version of babel-jest creates the problem
npm install --save-dev babel-jest#22.4.3
I had the same issue and the reason was that babel-jest has been upgraded to the latest version without upgrading the rest jest-related modules:
"babel-jest": "^26.6.3",
"jest": "^23.6.0",
In my case upgrading jest to the latest version fixed the issue:
"babel-jest": "^26.6.3",
"jest": "^26.6.3",
I ran into this problem because my jest.config.js had an incorrect transform. Per the babel-jest docs add:
"transform": {
"\\.[jt]sx?$": "babel-jest"
},
Probably the problem is the version of the "babel-jest" module. Try to allineate it with the "jest" module.
These are my dependencies in my package.json:
...
"babel-jest": "^23",
"jest": "22.4.3",
...

Jest - ReferenceError: define is not defined

I'm trying to use jest to start doing some unit testing but I've come across this error that a lot of people seem to be getting but I can't seem to figure it out.
Here's is what I'm trying to do (and I realize requirejs isn't supported):
jest.mock("../widgets/", () => {
return <button>button</button>;
});
describe('TextInput', () => {
describe('when user inputs a value', () => {
it('calls correct function to handle change', () => {
const handleChange = jest.fn();
const value = "test"
const wrapper = shallow(<TextInput handleChange={handleChange} />);
const textInputElement = wrapper.find("#textfield");
textInputElement.simulate('change', {target: { value }})
expect(handleChange).toHaveBeenCalledTimes(1);
});
});
});
import React from "react";
import ReactDOM from "react-dom";
import * as TestUtils from "react-dom/test-utils";
import { TextInput } from "../widgets/";
and here is my package.json
"jest": {
"collectCoverageFrom": [
"src/**/*.js"
],
"setupFiles": [
],
"testMatch": [
"**/src/**/?(*.)+(test).js"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js)$": "./node_modules/babel-jest",
"^.+\\.css$": "./config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|mjs|css|json)$)": "./config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx",
"node",
"mjs"
]
}
Upon running jest, I get the error ReferenceError: define is not defined and here is a more detailed error:
I would appreciate any help! Been pulling my hair out over this for the past few days :-(
Edit: Just realized that according to docs toHaveBeenCalledTimes should in fact also work. Anyway you could give mock.calls.length a try.
As far as I know assertions on jest function mocks do not work like this
expect(handleChange).toHaveBeenCalledTimes(1);
You should give this a try
expect(handleChange.mock.calls.length).toBe(1);
As described in the docs

Why is file not being imported - testing VueJS with Jest

I've gotten the basic setup for unit testing VueJS with Jest configured, and have successfully tested other components in a similar fashion, but for one particular file I'm importing the file to be tested and it's being logged as undefined.
/* Test */
import transition from '#/components/mixins/transition'
/* The '#' aliases the src directory which has been validated
for other components */
describe('transition mixin', () => {
it('should invoke transition correctly', () => {
console.log('transition: ', transition)
/* logs transition: undefined when suite is run */
})
})
Directory structure:
src
-components
--mixins
---transition.js
This is what transitions.js looks like:
/* transitions.js, not much to see here */
export const transition = {
props: {...},
computed: {...},
methods: {...}
}
Here is the jest.conf.js file although there's nothing here (to me) that suggests the transition.js mixin file to be tested would be excluded:
/* jest.conf.js */
const path = require('path')
module.exports = {
rootDir: path.resolve(__dirname, '../../'),
browser: true,
moduleFileExtensions: [
'js',
'json',
'vue'
],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1'
},
transform: {
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
'.*\\.(vue)$': '<rootDir>/node_modules/vue-jest'
},
snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
setupFiles: ['<rootDir>/test/unit/setup'],
coverageDirectory: '<rootDir>/test/unit/coverage',
collectCoverage: true,
collectCoverageFrom: [
'src/**/*.{js,vue}',
'!src/main.js',
'!src/router/index.js',
'!**/node_modules/**'
]
}

Categories