I've been having difficulties with Jest ever since I tried to begin using it. No tests I try to run and with what options I try to pass Jest, I never get the 'Pass' / 'Fail' output results in the console.
Jest always just outputs 'Done'
Using the 'Nuxt CLI' there is a default test written as:
import { mount } from '#vue/test-utils'
import Logo from '#/components/Logo.vue'
describe('Logo', () => {
test('is a Vue instance', () => {
const wrapper = mount(Logo)
expect(wrapper.isVueInstance()).toBeTruthy()
})
})
So far I have tried:
yarn test
yarn test --verbose
yarn test --watch
yarn test --watchAll
yarn test --no-watchmen
Every single time, the result is as follows:
yarn run v1.21.1
$ jest
Done in 0.72s.
Current jest.config.js:
module.exports = {
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/$1',
'^~/(.*)$': '<rootDir>/$1',
'^vue$': 'vue/dist/vue.common.js'
},
moduleFileExtensions: ['js', 'vue', 'json'],
transform: {
'^.+\\.js$': 'babel-jest',
'.*\\.(vue)$': 'vue-jest'
},
collectCoverage: true,
collectCoverageFrom: [
'<rootDir>/components/**/*.vue',
'<rootDir>/pages/**/*.vue'
]
}
This seems to be the default config for Nuxt.
Any help would be appreciated
So I figured it out (kind-of).
My tests run fine with the following:
yarn test --no-watchman
I can't figure out why watchman is causing me so many issues but this does seem to help.
More Info:
https://github.com/facebook/jest/issues/2219
Jest looks for files ending with .spec.js or .test.js file formats. Try putting your test in a file ending with .spec.js or .test.js file. Also you can configure jest, using jest.config.js file.
One such example of using jest.config.js file is
const path = require('path')
module.exports = {
rootDir: path.resolve(__dirname),
moduleFileExtensions: [
'js',
'json',
'vue',
'ts'
],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1'
},
transform: {
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest",
"^.+\\.(js|jsx)?$": "<rootDir>/node_modules/babel-jest",
"^.+\\.ts$": "<rootDir>/node_modules/ts-jest"
},
testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
snapshotSerializers: [
"jest-serializer-vue"
],
testEnvironment: "jsdom",
setupFiles: [
"<rootDir>/globals.js"
]
}
Related
I am going to test below component
WalletButton.jsx
import React from 'react';
import { WalletDialogButton } from "#solana/wallet-adapter-material-ui";
function WalletButton() {
return (
<WalletDialogButton>
{"CONNECT"}
</WalletDialogButton>
);
}
export default WalletButton;
The test case is below:
wallet-button.test.js
import {shallow} from "enzyme"
import React from 'react'
import WalletButton from "./WalletButton";
it('render WalletButton Component', () => {
expect(shallow(<WalletButton/>)).toMatchSnapshot();
})
When I run npm test, it shows error
● 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:
/Users/CCCC/Desktop/SourceTree/my-project/node_modules/#solana/wallet-adapter-material-ui/lib/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './useWalletDialog';
I attempt to add
transformIgnorePatterns: [
"node_modules/(?!#solana/wallet-adapter-material-ui)",
]
in jest.config.js but still not working.
How to fix it?
jest.config.js
module.exports = {
moduleDirectories: ["node_modules", "src"],
moduleNameMapper: {
"^#/(.*)$": "<rootDir>/src/$1",
"\\.(css|scss)$": "identity-obj-proxy",
},
transform: {
"^.+\\.(js|jsx)$": "babel-jest",
".+\\.(png|jpg|svg|ttf|woff|woff2)$": "jest-transform-stub",
},
transformIgnorePatterns: [
"node_modules/(?!#solana/wallet-adapter-material-ui)",
],
setupFilesAfterEnv: ["<rootDir>/src/setupTests.js"],
snapshotSerializers: ["enzyme-to-json/serializer"],
};
Update 1
babelrc
{
"presets": [
"#babel/preset-env",
["#babel/preset-react", { "runtime": "automatic" }]
]
}
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'
},
...
I have the following test:
jest.mock('#my-company/my-package/dist/browser');
import { broadcast } from '#my-company/my-package/dist/browser';
...
The file it is importing looks something like this within the node_modules folder:
import someFunction from '#my-company/some-other-package';
...
This is throwing the following error message when I run the test:
Cannot find module '#my-company/some-other-package' from 'browser.js'
Why would I be getting this error?
I have been going through my jest config file and can't spot anything that might be wrong. Here is the config file:
module.exports = {
testPathIgnorePatterns: [
'/node_modules/',
'/bower_components/',
'/cypress/',
'/test/', // test directory contains mocha and chai tests for now
],
transform: {
'.(js|jsx)': '#sucrase/jest-plugin',
},
transformIgnorePatterns: [`node_modules/(?!#my-company/my-package)`],
resolver: '#my-company/jest-bower-resolver',
setupFilesAfterEnv: ['<rootDir>/test/setup-tests.js'],
moduleDirectories: ['node_modules', 'bower_components', "<rootDir>"],
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/*.spec.js',
'!**/test/**',
'!**/test-jest/**',
'!**/cypress/**',
'!**/coverage/**',
'!**/node_modules/**',
'!**/bower_components/**',
'!**/public/**',
],
coverageDirectory: '<rootDir>/coverage/',
};
It is important to note that the package #my-company/my-package must be added to transformIgnorePatterns part of the config otherwise it won't be transpiled
Thanks
Recently I've moved a project from plain old JavaScript to TypeScript. Previously every test was running fine. Right after the change some test cases just broke and I can not understand why. I'm using Vue.js alongside vue-test-utils and jest.
jest.config.js
module.exports = {
collectCoverageFrom: [
'/src/**/*.{js,jsx,vue}',
'!**/node_modules/**',
'!**/vendor/**',
],
moduleFileExtensions: [
'ts',
'js',
'json',
'vue',
],
transform: {
'.*\\.(vue)$': 'vue-jest',
'^.+\\.js$': 'babel-jest',
'^.+\\.ts$': 'ts-jest',
},
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!vuex-class-modules).+\\.js$',
],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1',
},
setupFilesAfterEnv: [
'#testing-library/jest-dom/extend-expect',
],
};
A snippet of an example test that's failing right now, which has been working fine previously.
some.test.js
function mountStore(loggedInState) {
const store = new Vuex.Store({
modules: {
customer: {
namespaced: true,
state: {
isLoggedIn: loggedInState,
},
actions,
},
},
});
return shallowMount(Component, {
localVue,
store,
router,
stubs: { 'router-link': RouterLinkStub },
});
}
describe('Test with customer logged in at beginning', () => {
let wrapper;
beforeEach(() => {
wrapper = mountStore(true);
});
it('should redirect to home if user is logged in on init', () => {
expect(wrapper.vm.$route.name).toBe('Home');
});
});
Regarding this specific test case, the result is as following.
expect(received).toBe(expected) // Object.is equality
Expected: "Home"
Received: null
I also noticed upgrading all dependencies (including some Jest dependencies) leads to even more failing tests. So I expect that to (probably) be the reason, since I just added TypeScript support later on. However, I don't know what dependency combination would lead to a faulty behavior.
Relevant dependencies I've updated, which eventually would lead to even more failing tests.
jest
ts-jest
babel-jest
Add
preset: 'ts-jest/presets/js-with-babel',
to jest.config.js since you use ts-jest with babel-jest. Source.
Did you try adding #types/jest? And adding it in your tsconfig.json:
"types": ["#types/node", "#nuxt/types", "#types/jest", "nuxt-i18n"]
I was having a similar issue. #winwiz1's answer worked for me, but I needed to put it inside the project definition as I'm using the projects syntax. I would just leave this as a comment on #winwiz1's answer, but StackOverflow mangles the format.
projects: [
{
"displayName": "test-unit",
"preset": "ts-jest",
"testMatch": ["<rootDir>/test-unit/**/*\\.tests\\.[t|j]s"]
}
],
I'm using now.sh to deploy my nextjs (React) app. And the build is failing due to this error:
Build error occurred
ReferenceError: describe is not defined
Not sure why this started happening, here is my .babelrc
{
"env": {
"development": {
"compact": false,
"presets": [
"next/babel",
"#zeit/next-typescript/babel"
],
"plugins": [
["styled-components", {"ssr": true, "displayName": true}],
["#babel/plugin-proposal-decorators", {"legacy": true}]
]
},
"production": {
"presets": [
"next/babel",
"#zeit/next-typescript/babel"
],
"plugins": [
["styled-components", {"ssr": true, "displayName": true}],
["#babel/plugin-proposal-decorators", {"legacy": true}]
]
},
"test": {
"compact": false,
"presets": [
"#babel/preset-typescript",
["next/babel", {"preset-env": { "modules": "commonjs" }}]
],
"plugins": [
["styled-components", { "ssr": true, "displayName": true }],
["#babel/plugin-proposal-decorators", { "legacy": true }],
["babel-plugin-sass-vars"]
]
}
}
}
package.json
"engines" : {
"node" : ">=8.10.0 <11.0.0"
},
"scripts": {
"dev": "NODE_ENV=development next -p 7777",
"build": "NODE_ENV=production next build",
"start": "next -p 7777",
"test": "NODE_ENV=test jest --no-cache",
"test-watch": "NODE_ENV=test jest --watch --no-cache",
"coverage": "NODE_ENV=test jest --coverage",
"update-snap": "NODE_ENV=test jest --updateSnapshot"
},
Full log:
running "npm run now-build"
> moon.holdings#2.0.0 now-build /tmp/7418164
> next build
Creating an optimized production build ...
> Using external babel configuration
> Location: "/tmp/7418164/.babelrc"
> Build error occurred
ReferenceError: describe is not defined
at Module.kAI8 (/tmp/7418164/.next/serverless/pages/__tests__/about.test.js:63996:1)
at __webpack_require__ (/tmp/7418164/.next/serverless/pages/__tests__/about.test.js:23:31)
at module.exports.+3sd.exports.__esModule (/tmp/7418164/.next/serverless/pages/__tests__/about.test.js:91:18)
at Object.<anonymous> (/tmp/7418164/.next/serverless/pages/__tests__/about.test.js:94:10)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
npm
ERR! code ELIFECYCLE
The first test where the describe is used:
import React from 'react'
import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json'
import About from '../about.tsx'
describe('<About /> component', () => {
describe('rendering', () => {
const wrapper = shallow(<About />);
it('should render a component matching the snapshot', () => {
const tree = toJson(wrapper);
expect(tree).toMatchSnapshot();
expect(wrapper).toHaveLength(1);
expect(wrapper.contains(<About/>));
});
});
});
next.config
module.exports = (phase, { defaultConfig }) => {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
module: {
loaders: [
{
test: /\.json$/,
loader: 'json-loader'
}
]
}
// Note: Nextjs provides webpack above so you should not `require` it
// Perform customizations to webpack config
// Important: return the modified config
config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
return config
}
// ✅ Put the require call here.
const withTypescript = require('#zeit/next-typescript')
const withCSS = require('#zeit/next-sass')
// withCSS({target: 'serverless'})
return withTypescript(withCSS({
webpack(config, options) {
return config
}
}))
}
I removed the tests that covered the /pages directory. NextJS used pages for routing. Not sure why that was causing the problem, ran coverage and looks like pages wasn't necessary to cover.
Hoping for a better answer from someone at the NextJS / Now.sh team, and I'll select that.
Easy fix: https://github.com/zeit/next.js/issues/3728#issuecomment-523789071
pageExtensions: ['page.tsx']
An option that allows the tests inside pages folder:
change webpack settings direct in next.config.js
module.exports = {
webpack: (config, { webpack }) => {
config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
return config
}
}
It is ignoring whatever __tests__ folder found on the build process.
If you are looking to colocate non-page files with pages in the /pages directory, you can use Custom Page Extensions to force your pages to have a file extension of .page.js. Once that is setup, Next.js will ignore any files that don't have .page in the file extension.
next.config.js
module.exports = {
// Force .page prefix on page files (ex. index.page.tsx) so generated files can be included in /pages directory without Next.js throwing build errors
pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js'],
}
I wrote some docs for this use case that have yet to be merged https://github.com/vercel/next.js/pull/22740. The docs link above now contains these changes.
The original Github issue where this was discovered is https://github.com/vercel/next.js/issues/3728#issuecomment-895568757.