Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: Array.sort in hoist-jest might reversing all statements #4185

Open
hanjunspirit opened this issue Jul 12, 2023 · 2 comments
Open

[Bug]: Array.sort in hoist-jest might reversing all statements #4185

hanjunspirit opened this issue Jul 12, 2023 · 2 comments

Comments

@hanjunspirit
Copy link

hanjunspirit commented Jul 12, 2023

Version

27.1.5

Steps to reproduce

for the code:

class Base {
  sum(a: number, b: number) {
    return a + b;
  }
}
class MMath extends Base {}
export { MMath };

Expected behavior

Actual behavior

It will be compiled into:

export { MMath };
class MMath extends Base {
}
class Base {
    sum(a, b) {
        return a + b;
    }
}

This leads to Base class not being found, causing an error.

Debug log

Additional context

This piece of code has different results in different versions of Node.js:
[1,2,3].sort(() => 1)

For example,
in Node.js 10.24.0, it returns [3, 2, 1],
But in Node.js 12.18.3, it returns [1, 2, 3]

This depends on the implementation of the sort algorithm, and the result is unstable.

So for the sort in hoist-jest(#3498), if all isJestGlobalImport and isHoistableStatement return false, it might reversing all statements.

Environment

Node: 10.24.0
Jest: 27.1.5
@tschoartschi
Copy link

@hanjunspirit I think I have a similar problem. How did you debug it? How did you get the compiled code? I think in my case also the order of the statements is somehow mixed up. Although I import the class definition on top of the file I get the following error:

ReferenceError: Cannot access 'Base' before initialization

I'm a little bit lost because I don't know how to debug and therefore I can not create a repo with reproduction and without a repo I can not create a bug report.

@tschoartschi
Copy link

If someone else has the same problem, we found a workaround that works for us (probably that's not possible in every project).

We were able to reference the problematic file in setupFiles (https://jestjs.io/docs/configuration#setupfiles-array) and now everything works as expected. For us, this is a good enough workaround because it unblocks us 🎉 and we can continue to work.

Nevertheless, a long-term solution would be better than a workaround. We also expect that the hoisting "feature" of jest breaks our code. It's super hard to create a repo that reproduces the problem. We think that our problem is very similar to what @hanjunspirit encountered.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants