2

Summary

I'm using Next.js to create both API and and Frontend app. Frontend uses react. To unit testing I'm using next/jest preset and jest as an unit testing library. I'm using @tenstack/react-query to state management and when I want to test page, it throws an error. In tests where I'm using jsdom environment I add

/**
 * @jest-environment jsdom
 */

in tests to API I'm using babel-jest that is default and no need anything

error that throws


    /path/to/project/node_modules/@tanstack/react-query/src/QueryClientProvider.tsx:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import * as React from 'react'
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

The error appers in test where I want to render page that uses react-query

jest.config.js

// jest.config.js
const nextJest = require('next/jest');

const createJestConfig = nextJest({
  dir: './'
});

const customJestConfig = {
  moduleDirectories: ['node_modules', '<rootDir>/'],
  transform: {
    '^.+\\.[t|j]sx?$': 'ts-jest'
  }
};

module.exports = createJestConfig(customJestConfig);

.babelrc

{
  "presets": ["next/babel","@babel/preset-env", "@babel/preset-typescript"],
  "plugins": [
    "babel-plugin-transform-typescript-metadata",
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    "babel-plugin-parameter-decorator"
  ]
}

I've tried these answers but unfortunatelly it didn't help.

1 Answer 1

1

I solved myself an issue by mocking library @tenstack/react-query. Here is an sample code

jest.mock('@tanstack/react-query/src/QueryClientProvider', () => ({
  QueryClientProvider: ({ children }) => children
}));

jest.mock('@tanstack/react-query', () => ({
  QueryClient: jest.fn(),
  useQueryClient: jest.fn(),
  useQuery: jest.fn(),
  useMutation: jest.fn().mockReturnValue({
    mutate: jest.fn(),
    isLoading: false
  })
}));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.