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.

eval() in code being tested not working in Jest.

See original GitHub issue

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

Bug

What is the current behavior?

eval() inside code being tested with Jest doesn’t work. Does it have to do with vm.runInContext? (see https://github.com/facebook/jest/issues/439)

reproduction

I have some code like this in a source file of mine which some tests are triggering:

            let Ctor

            if ( className ) eval( `Ctor = function ${ className }() {}` )
            else {
                // anonymous even in ES6+
                Ctor = ( () => function() {} )()
            }

            Ctor.prototype = { __proto__: Object.prototype, constructor: Ctor }

            return Ctor

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

Check out that branch, then:

To see the error run

npm i
npm test

To see the code working fine under normal execution, run

node src/test.js

Note, npm test runs Jest with builder,

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

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

There is already a debugger statement on the line before the problem, you’ll have to click play a few times until the first time that the code steps into the part of the conditional when className is truthy, and the value of className will be "Foo".

You can also place a conditional breakpoint on that line if you’re familiar with Chrome inspector (right click the line number, click “Add conditional breakpoint…”, then input "className === "Foo")

What is the expected behavior?

My test file currently does not use any libraries, only console.assert(), so I can run it with node test.js.

When I run it with node test.js, it works great!

When I run the test with Jest, it fails:

The eval() should work. But when the code reaches that part, the eval() seems to be running in some other context (other scope).

So what I see happen is this:


            let Ctor

            // Ctor is undefined here

            eval( `Ctor = function ${ className }() {}` )

            // Ctor is still undefined here

I was expecting Ctor to be assigned a function, and therefore no error in the execution of the test file.

Again, this all works fine under normal Node execution of the file, and in browsers, just not in Jest.

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',
}

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:closed
  • Created 5 years ago
  • Reactions:1
  • Comments:5

github_iconTop GitHub Comments

1reaction
trusktrcommented, Apr 7, 2018

To fix the problem on my end, I changed the code so it uses Function instead of eval:

            if ( className ) Ctor = new Function( `return function ${ className }() {}` )()

This seems to be nicer anyways because I don’t need anything from outer scope, and because the code I am evaluating is my own code in my own scope (not third party code) I can easily pass arguments into the new Function if needed. Well, I can easily pass specific arguments in for third party code too. So, Function seems better overall and more secure.

0reactions
github-actions[bot]commented, Apr 27, 2022

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Jest testing function that calls eval - javascript - Stack Overflow
I have a Vue TS project created with vue-cli 3.0. This is the function I will test:.
Read more >
Using with puppeteer - Jest
Generating code coverage for test files using Puppeteer is currently not possible if your test uses page.$eval , page.
Read more >
How to Test Asynchronous Code with Jest | Pluralsight
Tests passing when there are no assertions is the default behavior of Jest. If you want to avoid Jest giving a false positive,...
Read more >
Run jest for unit tests of modified files only | by SunCommander
The problem with this option is that once you commit or push your changes, it won't be able to find changed files so...
Read more >
Frontend testing standards and style guidelines - GitLab Docs
There are two types of test suites encountered while developing frontend code at GitLab. We use Jest for JavaScript unit and integration testing,...
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