Home > Enterprise >  expect(...).toBeInTheDocument is not a function after setting up
expect(...).toBeInTheDocument is not a function after setting up

Time:03-24

I have '@testing-library/jest-dom' installed so it should be there. Also have the below imports, anything wrong with my config?

TypeError: expect(...).toBeInTheDocument is not a function

      52 |     renderIt(onSubmit);
      53 |
    > 54 |     expect(screen.getByText(/alberta/i)).toBeInTheDocument();

My test:

import { render, screen } from '@testing-library/react';
import { Formik, Form } from 'formik';

import { Select } from '.';

const options = [
  'Alberta',
  'British Columbia',
  'Manitoba',
  'New Brunswick',
  'Newfoundland & Labrador',
  'Northwest Territories',
  'Nova Scotia',
  'Nunavut',
  'Ontario',
  'Prince Edward Island',
  'Quebec',
  'Saskatchewan',
  'Yukon',
];

const renderIt = (onSubmit: () => void) => render(
  <Formik
    initialValues={{ province: '' }}
    onSubmit={onSubmit}
  >
    <Form>
      <Select name="province" options={options} />
    </Form>
  </Formik>,
);

describe('Select component', () => {
  test('It renders', () => {
    const onSubmit = jest.fn();
    renderIt(onSubmit);

    expect(screen.getByText(/alberta/i)).toBeInTheDocument();
  });
});

My src/setupTests.ts file:

// 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 '@testing-library/jest-dom/extend-expect';

package.json:

  "devDependencies": {
    "@testing-library/dom": "8.11.3",
    "@testing-library/jest-dom": "5.16.2",
    "@testing-library/react": "^13.0.0-alpha.6",
    "@testing-library/react-hooks": "7.0.2",
    "@testing-library/user-event": "13.5.0",
    "@types/jest": "27.4.1",
    "jest": "27.5.1",
    "ts-jest": "27.1.3",
    "typescript": "4.6.2"
  },

jest.config.js:

module.exports = {
  testEnvironment: 'jsdom',
  preset: 'ts-jest',
  moduleNameMapper: {
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/__mocks__/fileMock.js',
    '\\.(css|less)$': 'identity-obj-proxy',
  },
};

CodePudding user response:

You should declare the setupTests.ts in you jest configuration using the setupFilesAfterEnv property.

jest.config.js

module.exports = {
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
  preset: 'ts-jest',
  moduleNameMapper: {
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/__mocks__/fileMock.js',
    '\\.(css|less)$': 'identity-obj-proxy',
  },
};

  • Related