question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Wrong lines are shown in Jest output (for errors or failed expectations)0

See original GitHub issue

Do you want to request a feature or report a bug?

Bug?

What is the current behavior?

Line numbers for errors or failed expectations are wrong.

reproduction

Reproduction: https://github.com/trusktr/lowclass/tree/jest-issue-5942

Check out that branch, then to see the error run

npm i
npm test

Note, npm test runs Jest with builder,

To run the Jest test manually (for ease in debugging), you can run this command:

❯ node --inspect-brk ./node_modules/.bin/jest --config ./node_modules/builder-js-package/config/jest.config.js

The failed expectation is on line 886 of src/test.js but Jest reports a line of 896 and shows the wrong part of the code in the output.

What is the expected behavior?

I am expecting to see something like

    expect(received).toBe(expected) // Object.is equality

    Expected value to be:
      true
    Received:
      undefined

    Difference:

      Comparing two different types of values. Expected boolean but received undefined.

      884 |        // provide a hint on how we can make it work (traverse towards leaf of
      885 |        // the private prototype chain and find the instance)
    > 886 |        expect( b.testedFail ).toBe( true )
      887 |
      888 |        // native `super` works too:
      889 |        const Baz = Class().extends(Bar, ({Super}) => ({

      at Object.<anonymous>.test (src/test.js:886:30)

but instead I am seeing

    expect(received).toBe(expected) // Object.is equality

    Expected value to be:
      true
    Received:
      undefined

    Difference:

      Comparing two different types of values. Expected boolean but received undefined.

      894 |             }
      895 |         }))
    > 896 |
      897 |         const baz = new Baz
      898 |         baz.test()
      899 |         baz.testFail()

      at Object.<anonymous>.test (src/test.js:896:30)

Please provide your exact Jest configuration

module.exports = {
    rootDir: process.cwd(),

    transform: {
        '^.+\\.js$': path.resolve(__dirname, 'babel-jest'),
    },

    // a great environment that supports Custom Elements
    testEnvironment: '@skatejs/ssr/jest',
}

where the sibling babel-jest.js file contains

const CWD = process.cwd()

const babelJest = require('babel-jest')

module.exports = babelJest.createTransformer({
    presets: [
        ['env', {
            targets: {
                node: 6,
            },
        }],
    ],
})

Run npx envinfo --preset jest in your project directory and paste the results here

❯ npx envinfo --preset jest
npx: installed 1 in 2.41s

  System:
    OS: Linux 3.18
    CPU: x64 Intel(R) Core(TM) m3-6Y30 CPU @ 0.90GHz
  Binaries:
    Node: 9.9.0
    Yarn: 1.3.2
    npm: 5.8.0

❯ cat node_modules/jest/package.json | grep version
  "version": "22.4.3"

Jest is not installed globally

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:7
  • Comments:9

github_iconTop GitHub Comments

1reaction
ChenRothcommented, Aug 1, 2018

happens to me with jest 23.4.1 and ts-jest 23.0.1

0reactions
Cielquancommented, Dec 9, 2022

I came across this issue as I was having the same problem and in my case I could track it down to multiline docstrings.

Working example

I have a helper function and added a docstring to it. The single line variant does work as expected.

/** Single line docstring */
const helper = (): number => 2;

describe("test case", () => {
  it("shows wrong line number on error", () => {
    const result = 1 + helper();

    expect(result).toBe(4);
  });
});

export {};
$ yarn test-jest-ci __tests__/issue5942Repro.test.ts 
 FAIL  __tests__/issue5942Repro.test.ts
  test case
    × shows wrong line number on error (3 ms)

  ● test case › shows wrong line number on error

    expect(received).toBe(expected) // Object.is equality

    Expected: 4
    Received: 3

       6 |     const result = 1 + helper();
       7 |
    >  8 |     expect(result).toBe(4);
         |                    ^
       9 |   });
      10 | });
      11 |

      at Object.<anonymous> (__tests__/issue5942Repro.test.ts:8:20)

Broken example

When I change the docstring to be multiline, the issue occurs.

/** Multiline docstring
 */
const helper = (): number => 2;

describe("test case", () => {
  it("shows wrong line number on error", () => {
    const result = 1 + helper();

    expect(result).toBe(4);
  });
});

export {};
$ yarn test-jest-ci __tests__/issue5942Repro.test.ts 
 FAIL  __tests__/issue5942Repro.test.ts
  test case
    × shows wrong line number on error (3 ms)

  ● test case › shows wrong line number on error

    expect(received).toBe(expected) // Object.is equality

    Expected: 4
    Received: 3

       8 |
       9 |     expect(result).toBe(4);
    > 10 |   });
         |   ^
      11 | });
      12 |
      13 | export {};

      at Object.<anonymous> (__tests__/issue5942Repro.test.ts:10:3)

Additional Information

I have a typescript nextJS v13 project and created the above test case in it.

The run script is this: "test-jest-ci": "jest --ci", and I cut the coverage report off.

$ npx envinfo --preset jest

  System:
    OS: Windows 10 10.0.19042
    CPU: (12) x64 12th Gen Intel(R) Core(TM) i7-1265U
  Binaries:
    Node: 18.12.1 - C:\Program Files\nodejs\node.EXE 
    Yarn: 3.2.1 - ~\AppData\Roaming\npm\yarn.CMD     
    npm: 8.19.2 - C:\Program Files\nodejs\npm.CMD

$ cat node_modules/jest/package.json | grep version
  "version": "29.3.1",

jest.config.ts

import type { Config } from "jest";
import nextJest from "next/jest";

// Sync object
const createNextJestConfig: (customJestConfig?: Config) => () => Promise<Config> = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test
  // environment
  dir: "./",
});

// Add any custom config to be passed to Jest
const customJestConfig: Config = {
  // Add more setup options before each test is run
  setupFilesAfterEnv: ["@testing-library/jest-dom"],
  // if using TypeScript with a baseUrl set to
  // the root directory then you need the below for alias' to work
  moduleDirectories: ["../../node_modules", "<rootDir>/"],
  testEnvironment: "jest-environment-jsdom",
  modulePathIgnorePatterns: ["cypress"],
  transformIgnorePatterns: ["/node_modules/(?!jose)/"],
  clearMocks: true,
  resetMocks: true,
  restoreMocks: true,
  collectCoverage: true,
  collectCoverageFrom: ["src/**/*.{ts,tsx}"],
  coverageDirectory: "../../.coverage_cache/swlp_frontend",
  coverageThreshold: {
    global: {
      branches: 100,
      functions: 100,
      lines: 100,
      statements: 100,
    },
  },
};

/** Removes "node_modules" from "transformIgnorePatterns" added by nextJS. */
const removeNodeModulesFromConfig = (jestConfig: Config): Config => {
  if (jestConfig.transformIgnorePatterns === undefined) return jestConfig;
  const idx = jestConfig.transformIgnorePatterns.findIndex((v: string) =>
    v.includes("node_modules"),
  );
  jestConfig.transformIgnorePatterns.splice(idx, 1);

  return jestConfig;
};

const createCustomJestConfig = async (): Promise<Config> => {
  const nextJestConfig = await createNextJestConfig(customJestConfig)();
  return removeNodeModulesFromConfig(nextJestConfig);
};

export default createCustomJestConfig;
Read more comments on GitHub >

github_iconTop Results From Across the Web

Jest CLI Options
The jest command line runner has a number of useful options. You can run jest --help to view all available options. Many of...
Read more >
Why does Jest throw an error when it should not?
Tests only fail if there is an unmet expectation. In your case, because no error is thrown, no expectation is ever even evaluated....
Read more >
Component testing scenarios - Angular
In a spec with multiple expectations, it can help clarify what went wrong and which expectation failed. The remaining tests confirm the logic...
Read more >
jest-junit - npm
Note: as of jest-junit 11.0.0 NodeJS >= 10.12.0 is required. ... Reports test suites that failed to execute altogether as error .
Read more >
How to find the root cause of a failing test if Jest doesn't tell ...
The issue seems to occur more likely in Angular projects when using Node 14. How to get the actual error message in Jest...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found