João Pedro
João Pedro

Reputation: 1

Individual test passes, but fails with --coverage in Jest. Why?

I'm facing an issue running my tests with Jest in a React Native project. When I run the tests individually (using the command to run a specific test), they pass without a hitch. However, when I run Jest with the --coverage flag to generate the coverage report, the test fails or throws an error.

Here is some relevant information:

I use transformIgnorePatterns in my Jest config file to include/exclude certain modules from being transformed. The failure occurs only when running with --coverage. Without the flag, everything works correctly. I'm using various dependencies from React Native and other libraries such as @react-native-community, expo, native-base, among others. I'm trying to understand why the test passes individually but fails with the coverage report, and whether this might be related to the transform settings or some other specific setting.

Here running the test individually enter image description here

jest.config.ts

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
import jestPreset from "@testing-library/react-native/jest-preset";

import { type Config } from "jest";

const coveragePercentage = 90;
const ignorePaths = [
    "./src/test/",
    "./src/utils/test.ts",
    "./src/@types/test.ts",
    "./src/test/jest.setup.ts",
];

export default {
    verbose: true,
    preset: "jest-expo",
    setupFiles: [
        ...jestPreset.setupFiles,
        "<rootDir>/src/test/mocks/modules/i18n-js/index.ts",
        "<rootDir>/src/test/mocks/modules/async-storage/index.ts",
        "<rootDir>/src/test/mocks/modules/@nozbe/watermelondb/index.ts",
        "<rootDir>/src/test/mocks/modules/@sendbird/uikit-react-native-foundation/index.ts",
        "<rootDir>/src/test/mocks/modules/@sendbird/uikit-react-native/index.ts",
    ],
    setupFilesAfterEnv: ["@testing-library/react-native/extend-expect", "./src/test/jest.setup.ts"],
    // eslint-disable-next-line array-bracket-newline
    transformIgnorePatterns: [
        "node_modules/(?!(jest-)?react-native|@react-native(-community)?|expo(nent)?|@expo(nent)?/.*|@expo-google-fonts/.*|react-navigation|@react-navigation/.*|@unimodules/.*|unimodules|sentry-expo|native-base|react-native-svg|react-redux|@sendbird/uikit-react-native-foundation|@miblanchard/react-native-slider)",
        // eslint-disable-next-line array-bracket-newline
    ],
    bail: true,
    forceExit: true,
    testTimeout: 20000,
    detectOpenHandles: true,
    testPathIgnorePatterns: [...ignorePaths],
    collectCoverage: false,
    coveragePathIgnorePatterns: [...ignorePaths, "./src/config/reactotron.ts"],
    collectCoverageFrom: [
        "./src/**/*.{ts,tsx}",
        "!./src/**/*.stories.tsx",
        "!./src/**/animations.ts",
    ],
    coverageDirectory: "./coverage",
    coverageProvider: "babel",
    coverageReporters: ["lcov", "html"],
    coverageThreshold: {
        global: {
            branches: coveragePercentage,
            functions: coveragePercentage,
            statements: coveragePercentage,
            lines: coveragePercentage,
        },
    },
    logHeapUsage: true,
    rootDir: "../../",
    clearMocks: true,
    resetMocks: false,
    resetModules: false,
    moduleNameMapper: {
        ".(jpg|jpeg|png|gif|webp|svg)$": "<rootDir>/src/test/mocks/fileMock.js",
        ".(css|less)$": "<rootDir>/src/test/mocks/styleMock.js",
        "^@sendbird/uikit-react-native-foundation(.*)$": "<rootDir>/src/test/mocks/sendbirdMock.js",
        "^assets/(.*)$": "<rootDir>/assets/$1",
    },
    transform: {
        "^.+\\.jsx?$": "babel-jest",
    },
} as Config;

test.tsx

import React from "react";
import { Provider } from "react-redux";

import { store } from "@b2list/store/store";
import { render } from "@testing-library/react-native";

import { CheckBox } from "./CheckBox";

jest.mock("expo-asset");
jest.mock("expo-font");
jest.mock("react-native-reanimated", () => require("react-native-reanimated/mock"));

describe("CheckBox component", () => {
    it("Deverá renderizar o texto do checkbox", () => {
        const { getByText } = render(
            <Provider store={store}>
                <CheckBox text="Check this box" onStateChange={() => { } } value={false} />
            </Provider>
        );
        const checkBoxText = getByText("Check this box");

        expect(checkBoxText).toBeTruthy();
    });

});

Here npx jest --coverage enter image description here

● Test suite failed to run
                                                                                         
    Jest encountered an unexpected token                                                 
                                                                                         
    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.  
                                                                                         
    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.                                               

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • 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/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    C:\app\b2mobile-ui\node_modules\react-redux\dist\react-redux.legacy-esm.js:34        
    import * as React2 from "react";
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | import React from "react";
    > 2 | import { Provider } from "react-redux";
        | ^

I want that when running the --coverage flag, a coverage report of the checkbox component is generated to see what still needs to be covered.

Upvotes: 0

Views: 80

Answers (0)

Related Questions