next/jest feedback #31152
Replies: 45 comments 72 replies
-
Hello! 👋 @timneutkens Thanks for making Ideas of improvements
import i18n from 'i18n.json' With the current config, this is not working in
|
Beta Was this translation helpful? Give feedback.
-
continuing from #30174 (comment)
|
Beta Was this translation helpful? Give feedback.
-
Thanks for bringing this forward! We tried it and unfortunately some of our tests are failing, for example:
See the CI log for all errors, with the following Next.js folder and this jest.config.js. |
Beta Was this translation helpful? Give feedback.
-
I got two different issues my first one I'm pretty sure is the same as, @martinfrancois 's. My guess is that the magical auto-hoisting of jest.mock calls after transpiling into commojs present on babel-jest is not working / has not been ported? I got the following stack trace:
Which for me makes the error pretty obvious, the only way for The second issue I got is because I'm using some libraries that already have been ported to native node ESM modules. (e.g. react-markdown) the work around I was using is to transpile those modules by whitelisting them in |
Beta Was this translation helpful? Give feedback.
-
Hello! I've noticed that next/jest forces diff --git a/examples/with-jest/__tests__/index.test.jsx b/examples/with-jest/__tests__/index.test.jsx
index b2fc240af..a24d6117f 100644
--- a/examples/with-jest/__tests__/index.test.jsx
+++ b/examples/with-jest/__tests__/index.test.jsx
@@ -16,4 +16,8 @@ describe('Home', () => {
expect(heading).toBeInTheDocument()
})
+
+ it('runs in test environment', () => {
+ expect(process.env.NODE_ENV).toEqual('test')
+ })
}) And it results in:
|
Beta Was this translation helpful? Give feedback.
-
I seem to be having a similar issue to @samuelhnrq and @martinfrancois above. Mocking doesn't seem to be working correctly. I've set up an example repo here to demonstrate. Basically, if you call |
Beta Was this translation helpful? Give feedback.
-
I am having issues with getting jest mocks to work when I am using Such as:
or
But mostly see the first happen in my tests. One of my problematic unit tests: jest.mock('@/utils/analytics', () => ({
handleAppClose: jest.fn(),
}))
describe('WidgetLayout', () => {
beforeEach(() => {
jest.resetAllMocks()
})
test('triggers CLOSE event when clicking on modal background', () => {
const DummyComponent = () => <div>Lego or K’Nex</div>
const { container } = renderElement(
<WidgetLayout>
<DummyComponent />
</WidgetLayout>,
)
expect(screen.getByText(/Lego/i)).toBeInTheDocument()
const modalBackground = container.getElementsByTagName('div')[0]
userEvent.click(modalBackground)
expect(handleAppClose as jest.Mock).toHaveBeenCalledWith(
widget-name',
expect.anything(),
)
})
}) |
Beta Was this translation helpful? Give feedback.
-
I've encountered issues related to mocking similar to the ones mentioned here already. In addition I wasn't able to temporarily set Here's an isolated reproduction to play with: https://github.com/lfjsa/swc-jest-window-test. Deets in the Readme. |
Beta Was this translation helpful? Give feedback.
-
Something I'd love to see better documented is using TypeScript and/or ESM. In particular, I'm running into a lot of "Unexpected token" errors due to dependencies'
Additionally, it seems like
That utility makes life a lot easier with TSConfig, so it would be nice to have functioning here |
Beta Was this translation helpful? Give feedback.
-
Ive noticed that when running tests locally on my machine by running the command
But on Vercel, it only loads the
My workaround for now has been to add the
|
Beta Was this translation helpful? Give feedback.
-
Did anyone run into the problem, that Jest doesn't run for components with the following error:
It seems to be running under babel, but at the top I see, that
I don't have a babelrc file. Any ideas? |
Beta Was this translation helpful? Give feedback.
-
Hi, do you get correct coverage and line numbers? My jest.config.js:const nextJest = require("next/jest")
const createJestConfig = nextJest({ dir: "." })
// for reference, what's included and how the overrides work:
// https://github.com/vercel/next.js/blob/canary/packages/next/build/jest/jest.ts
const customJestConfig = {
moduleDirectories: ["node_modules", "src/test"],
moduleNameMapper: {
"@/components/(.*)": "<rootDir>/src/components/$1",
"@/features/(.*)": "<rootDir>/src/features/$1",
"@/graphql/(.*)": "<rootDir>/src/graphql/$1",
"@/pages/(.*)": "<rootDir>/src/pages/$1",
"@/theme/(.*)": "<rootDir>/src/theme/$1",
"@/types/(.*)": "<rootDir>/src/types/$1",
"@/utils/(.*)": "<rootDir>/src/utils/$1",
"@/test/(.*)": "<rootDir>/test/$1",
"@/toolsSetup/(.*)": "<rootDir>/toolsSetup/$1",
// jest has troubles resolving this import and it's easier to solve this single case
// manually here than looking for a robust config solution
// eslint-disable-next-line @typescript-eslint/naming-convention
"graphql-let/__generated__/__types__": "@types/graphql-let/__generated__/__types__.d.ts",
},
testEnvironment: "jsdom",
transform: {
"^.+\\.graphql$": [
"graphql-let/jestTransformer",
{ subsequentTransformer: "next/dist/build/swc/jest-transformer" },
],
},
setupFilesAfterEnv: ["<rootDir>/test/config/setupFiles.ts"],
// allow SWC to run on typescript code of generated types (to use schema model types)
// or cached types (to use enum's code), while still keeping mode_modules disabled
transformIgnorePatterns: ["node_modules/(?!graphql-let|@types/graphql-let|.cache/graphql-let)"],
testPathIgnorePatterns: ["<rootDir>/coverage/", "<rootDir>/test/e2e/"],
collectCoverageFrom: [
"src/**/*.{js,jsx,ts,tsx}",
"!**/*.stories.tsx",
// types (graphql, custom)
"!**/*.d.ts",
// example components, not used in production
"!**/examples/**",
],
}
const asyncConfig = createJestConfig(customJestConfig)
module.exports = async () => {
const config = await asyncConfig()
// next/jest ignores node_modules and allows to add more ignore patterns, but we need to override them fully to whitelist some node_modules
// https://github.com/vercel/next.js/blob/canary/packages/next/build/jest/jest.ts
config.transformIgnorePatterns = customJestConfig.transformIgnorePatterns
return config
} Adding this line to the "^.+\\.(js|jsx|ts|tsx)$": ["babel-jest", { presets: ["next/babel"] }], Coverage comparison - SWC on the left, Babel on the right: |
Beta Was this translation helpful? Give feedback.
-
Similar to what is described above, I have trouble with
The test that is failing is a very straight forward snapshot test of a navigation item component, for which I mock jest.mock('next/router', () => ({
useRouter: jest.fn().mockReturnValue({
asPath: '/some-path',
}),
}));
describe('NavigationItem', () => {
it('renders correctly', () => {
const { container } = render(
<NavigationItem href="/" title="Some Link" />
);
expect(container).toMatchSnapshot();
});
}); In the component I am using the const { asPath } = useRouter();
const isActive = asPath.startsWith(href); |
Beta Was this translation helpful? Give feedback.
-
I'm having trouble with mocking. I've extended the Here is the test for reference. import { render, screen } from '@testing-library/react'
import Home from '@/pages/index'
import {hello} from "@/utils/hello"
// doesn't work!
jest.mock("@/utils/hello")
const mockHello = hello as jest.MockedFunction<typeof hello>
mockHello.mockReturnValue("Hello World")
// doesn't error, but doesn't work!
jest.mock("@/utils/hello", () => {
return {hello: () => "Hello World"}
})
describe('Home', () => {
it('renders a heading', () => {
render(<Home />)
expect(screen.getByText("Hello World")).toBeInTheDocument()
})
}) I also tried mocking the module and providing an implementation. While this does compile correctly, it doesn't seem like it actually mocks the And here's the example repository. |
Beta Was this translation helpful? Give feedback.
-
Perhaps the new built-in Jest config could mock |
Beta Was this translation helpful? Give feedback.
-
I have this mapping for images in jest config:
And But the issue is that my snapshots have
That same image in code was imported like this This worked fine without swc. |
Beta Was this translation helpful? Give feedback.
-
Hey guys, we're trying to use module.exports = {
compiler: {
// ssr and displayName are configured by default
styledComponents: true,
},
}; and this is the jest.config.js file (just like the example in here: // jest.config.js
const nextJest = require('next/jest')
// Providing the path to your Next.js app which will enable loading next.config.js and .env files
const createJestConfig = nextJest({ dir })
// Any custom config you want to pass to Jest
const customJestConfig = {
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
}
// createJestConfig is exported in this way to ensure that next/jest can load the Next.js configuration, which is async
module.exports = createJestConfig(customJestConfig)
|
Beta Was this translation helpful? Give feedback.
-
this works for me with 12.1.6: Added webpack rules to next.config.js
This means you can include an SVG like:
or if you need a dataUrl for image src or a css background image:
svgStr.js:
svg.js
|
Beta Was this translation helpful? Give feedback.
-
This works for me (instead of // jest.config.js
moduleNameMapper: {
'^.+\\.(svg)$': '<rootDir>/__mocks__/svg.js',
}
moduleDirectories: ['node_modules', '<rootDir>/'] Thanks @GetafixIT |
Beta Was this translation helpful? Give feedback.
-
Since updating my lockfile in the last week or so I can no longer stub ES imports/exports using Descriptor for property default is non-configurable and non-writable Has there been any change to SWC or Related issue in TS from the past: |
Beta Was this translation helpful? Give feedback.
-
Hi Guys, We've found some TypeErrors when upgrading to [email protected] and testing with JEST: index.test
user.ts
We are using [email protected] with jest installed and configured as mentioned in the docs. P.S This is not happening with [email protected] We would really appreciate some feedback/fix/workarounds about it. |
Beta Was this translation helpful? Give feedback.
-
After upgrading Next to 12.3 from 12.1 we're seeing about 10% of all test suites failing with various errors.
So just to reiterate - the entire test suites passes just fine in 12.1 Any help or guidance is appreciated! We need the upgrade for one of the new features in 12.3. |
Beta Was this translation helpful? Give feedback.
-
jest.config.js const nextJest = require('next/jest') Error: Cannot find module 'next/jest'
|
Beta Was this translation helpful? Give feedback.
-
When using next/jest I've noticed three different issues I wanted to share:
|
Beta Was this translation helpful? Give feedback.
-
Switching all our Jest testing over to use SWC, and it mostly worked ok. Couple things - our tests for Stripe components aren't working as expected anymore. Not really sure what might cause it - mocks not working the same anymore? The more problematic one is that scss isn't auto mocked with something like |
Beta Was this translation helpful? Give feedback.
-
Could it be that the using |
Beta Was this translation helpful? Give feedback.
-
Error happen when combination v8-to-istanbul and swc (next/jest using this combination).
refs: istanbuljs/v8-to-istanbul#198
const conf = async () => {
const nextJestConfig = await createJestConfig()();
return {
...nextJestConfig,
transform: {
"^.+\\.(ts|tsx)$": [
"ts-jest",
{
tsconfig: "tsconfig.jest.json",
},
],
},
};
};
export default conf; |
Beta Was this translation helpful? Give feedback.
-
I'm having trouble setup With jest-babel works as expected, migrating to
here is the repro repo based on the |
Beta Was this translation helpful? Give feedback.
-
Hi, I got issue setting up Jest in my NextJS project, hope someone can help here is my jest.config.js (I've followed the with-jest example)
and got this error
|
Beta Was this translation helpful? Give feedback.
-
Hi All,
My Jest config:
|
Beta Was this translation helpful? Give feedback.
-
Feedback thread for the new experimental
next/jest
Jest transformer.Beta Was this translation helpful? Give feedback.
All reactions