Giter Club home page Giter Club logo

jest-electron-runner's Introduction

CircleCI

Jest electron runner

A custom test runner for Jest that runs tests inside an electron main or renderer process providing the following benefits:

  • Main

    • all electron instance modules (ipc, app, etc)
  • Renderer

    • full access to a browser environment without the need for jsdom or similar modules

Getting Started

NOTE: for jest@23 use the older version ~@jest-runner/[email protected]

  1. Install jest electron runner yarn add @jest-runner/electron --dev

  2. Add one of these lines to your jest config (in package.json or inside your jest.config.js file), depending on the process you wish to test. If you wish to test them in parallel, see the tips section below.

    • Main process
        {
          // ...
          runner: '@jest-runner/electron/main',
          testEnvironment: 'node',
        }
    • Renderer Process
        {
          // ...
          runner: '@jest-runner/electron',
          testEnvironment: '@jest-runner/electron/environment',
        }
  3. run jest!

Debugging

Normally jest-electron-runner runs a headless instance of electron when testing the renderer process. You may show the UI by adding this to your test:

require('electron').remote.getCurrentWindow().show();

Tips

  • The main process runner can be used to test any non-browser related code, which can speed up tests roughly 2x.
  • To run the main and renderer process tests in parallel, you can provide a config object to the projects array in a jest javascript config file like so:
// jest.config.js
const common = require('./jest.common.config')

module.exports = {
  projects: [
    {
      ...common,
      runner: '@jest-runner/electron/main',
      testEnvironment: 'node',
      testMatch: ['**/__tests__/**/*.(spec|test).ts']
    },
    {
      ...common,
      runner: '@jest-runner/electron',
      testEnvironment: '@jest-runner/electron/environment',
      testMatch: ['**/__tests__/**/*.(spec|test).tsx']
    }
  ]
}

Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read the full text so that you can understand what actions will and will not be tolerated.

Read our contributing guide to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to Jest.

License

MIT licensed.

jest-electron-runner's People

Contributors

aaronabramov avatar aguynamedben avatar bryanpierce avatar daniel-nagy avatar elliottsj avatar fitzpasd avatar jm-mendez avatar neojski avatar rajivshah3 avatar ralexmatthews avatar smacpherson64 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jest-electron-runner's Issues

how to keep the electron window?

require('electron').remote.getCurrentWindow().show();

add code above into test cases, can not work! The window flash and exit.

No longer works with Jest 27

Trying to run tests with jest-electron-runner and Jest 27 results in errors like this:

  ● Test suite failed to run

      ● Test suite failed to run

        TypeError: Cannot read property 'bind' of undefined

      at jestAdapter (node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapter.js:30:56)

Jest 27 changed the API of Jest Environments. I guess it has something to do with this. The runScript method is not used anymore. Instead the logic of it is executed directly in the runtime so looks like the environment can't override this behavior anymore. Not sure if this is the reason for the error above. Maybe more stuff is broken now.

Jest-electron-runner hangs on simple test

When using jest-electron-runner on a simple test: it starts running the test, launches electron process and then hangs without making a progress.

Removing jest-electron-runner makes the test run without issues.

Jest config:

module.exports = {
    "transform": {
        "^.+\\.tsx?$": "ts-jest"
    },
    "globals": {
        "ts-jest": {
            "tsConfig": "./tsconfig.json"
        }
    },
    "moduleFileExtensions": [
        "ts",
        "tsx",
        "js",
        "json",
        "node"
    ],
    "runner": "@jest-runner/electron/main",
    "testEnvironment": "node",
    "testMatch": ["**/test/**/*.(spec|test).ts"]
};

Test file:

describe("calculate", () => {
  it("add", () => {
    const result = 5 + 2;
    expect(result).toBe(7);
  });
});

Package.json dependencies versions:

{
    "devDependencies": {
        "@jest-runner/electron": "2.0.2",
        "@types/jest": "24.0.21",
        "@types/react": "16.9.11",
        "@types/react-dom": "16.9.3",
        "electron": "7.0.0",
        "fancy-log": "1.3.3",
        "gulp": "4.0.2",
        "gulp-changed": "4.0.2",
        "jest": "24.9.0",
        "ts-jest": "24.1.0",
        "tslint": "5.20.0",
        "typescript": "3.6.4"
    },
    "dependencies": {
        "react": "16.11.0",
        "react-dom": "16.11.0"
    }
}

How do you configure to run Atom package specs?

Is it possible to have this act as a test runner for Atom packages? I have "atomTestRunner": "@jest-runner/electron", in my package.json and runner and testEnvironment in my jest config, but I just get this error:

Error: Cannot find module 'jest-mock'
    at Module._resolveFilename (module.js:543:15)

Running tests in Electron main process

If I want to test a piece of code that's meant to run in Electron main process, is there anyway to configure jest-electron-runner to achieve that?

Currently require('electron').ipcRenderer can be imported and used, but require('electron').ipcMain is undefined.

Using require('electron').remote.ipcMain is not ideal because that would change the code to be tested - in actual execution it will be in main process

Does not work on Electron 12

The runner does not seem to work on Electron 12. By using

JEST_ELECTRON_RUNNER_RENDERER_THREAD_DEBUG_PORT=9222 jest

and inspecting the error, the problems seem to be in the new default settings and security policy of Electron 12 (nodeIntegration also requires contextIsolation=false but contextIsolation is true by default in Electron 12).

image

Not working in Jest 25.4.0 version

It's working after recent Jest updates. I get the following error:

TypeError: runtime.unstable_shouldLoadAsEsm is not a function
        at jasmine2 (node_modules/@jest/core/node_modules/jest-jasmine2/build/index.js:210:23)
        at node_modules/@jest-runner/electron/node_modules/jest-runner/build/runTest.js:385:24

Incompatible with Electron 5

The nodeIntegration flag in BrowserWindow webPreferences had a default value of true in earlier versions of Electron. The default value has changed to false in Electron 5. A value of true (i.e. the presence of the Node environment) is necessary for the test runner to run as it is currently written.

I've created a PR for this (#42), but rather than jumping through the CLA hoops, it's probably easier if someone who is already legally approved to contribute to this project just adds this minor change that amounts to passing an additional flag to one constructor call.

Mocks are undefined when using electron-runner 3.0.0 or 2.0.3 in combination with Jest 25+

Steps to reproduce:

  1. Clone this repository: https://github.com/dschuessler/jest-bug-example
  2. cd jest-bug-example && npm install && npx jest Notice the test passes.
  3. Now go to the package.json and raise either the version of jest to 25.0.0 or the version of @jest-runner/electron to 3.0.0
  4. rm -rf node_modules/ && npm install && npx jest

Expected behavior: The test still passes.

Actual behavior: The test fails. The mock is undefined.

    ✕ electron mock (9 ms)

  ● Strip › electron mock

    expect(received).toBeDefined()

    Received: undefined

       5 | describe("Strip", () => {
       6 |   test("electron mock", () => {
    >  7 |     expect(app).toBeDefined();
         |                 ^
       8 |   });
       9 | });
      10 | 

      at Object.<anonymous> (src/main/strip.test.ts:7:17)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        6.846 s

It's not working in Gitlab CI Server

Configurations

// jest.config.js
module.exports = {
  "roots": [
    "./src"
  ],
  "transform": {
    "^.+\\.tsx?$": "ts-jest"
  },
  runner: '@jest-runner/electron',
  testEnvironment: '@jest-runner/electron/environment',
}

Docker image

nikolaik/python-nodejs:latest

What happened?

The log below is shown after running the jest command, and then it remained hanging and nothing happened after that, no output at all.

> jest --maxWorkers=1

(process:4814): Gtk-WARNING **: Locale not supported by C library.
	Using the fallback 'C' locale.

(electron:4814): Gtk-WARNING **: cannot open display: 

Wrong .getAppPath result while running test

Hi!

I am getting wrong result of app.getAppPath() while running test.

How to reproduce?

Use app.getAppPath() somewhere inside you class, write test for this class, run test.

Actual result:

 C:\Users\Bohdan\projects\electron-first-try\node_modules\@jest-runner\electron\build

Expected result:

 C:\Users\Bohdan\projects\electron-first-try

Or maybe I have wrong configuration somewhere?

Unable to use enableRemoteModule in

Electron 10 has a breaking change that is that enableRemoteModule now defaults to false. Although migrating out of the use of the remote module is the best (and suggested) practiced, electron apps might still rely on the remove module and because jest-electron-runner has no option to force enableRemoteModule, running tests with electron 10 becomes impossible.

I have changed locally jest-electron-runner to use force enableRemoteModule and my tests started to work as expected. So my suggestion would be to make a configuration for enabling it, but I'm not sure how to do, or if it should indeed be done. I'm willing to take this issue, but I would like to hear from you on the best way of doing this.

To be honest, I'm not sure if there are other options (besides not using remote module), that would allow me to upgrade my app to electron 10, and still be able to run my tests with jest-electron-runner. So, f you have any inputs on this, I would be very grateful. :)

pending() fails with timeout in async tests

The following test fails with a timeout when run in Jest Electron environment. Works correctly in Node environment:

describe("foo", () => {
    it("bar", async () => {
        pending("Disabled");
        expect(await Promise.resolve("23")).toBe("23");
    });
});

Output is:

 FAIL  lib/test/support/foo.test.js (5.351s)
  foo
    ✕ bar (5005ms)

  ● foo › bar

    Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.

      1 | describe("foo", () => {
    > 2 |     it("bar", async () => {
        |     ^
      3 |         pending("Disabled");
      4 |         expect(await Promise.resolve("23")).toBe("23");
      5 |     });

      at Spec (node_modules/jest-jasmine2/build/jasmine/Spec.js:92:20)
      at Suite.it (lib/test/support/foo.test.js:2:5)

I'm using Jest 24.1.0 and Electron Runner 1.1.1.

Change window resizes to test responsiveness

We would like to be able to change the window size in a test to determine if code handling responsiveness is functioning correctly.

Doing simple window.resizeTo(...) calls does not update the window.innerWidth.

Tying into the Electron remote seems to make it a bit further, but still does not trigger anything. For example:

const currentWindow = require('electron').remote.getCurrentWindow();
currentWindow.setSize(1400, 1000);
console.log(currentWindow.getSize()); // Shows 1400!
console.log(window.innerWidth); // Still is 800

In either case, the resize window eventListener is never called.

Is this possible currently or is there a known defect that disallows this from happening? The draw of using Electron for these types of tests is to use browser APIs, such as this.

Fails to run on Gitlab CI

Configurations

jest.config.js

module.exports = {
    setupFiles: ["./test-setup.js"],
    runner: "@jest-runner/electron",
    testEnvironment: "@jest-runner/electron/environment",
    collectCoverageFrom: ["**/*.js", "!**/node_modules/**"],
    coverageReporters: ["text", "lcov"],
    testResultsProcessor: "jest-sonar-reporter"
};

.gitlab-ci.yml

validation:
    stage: validation
    before_script:
        - apt-get update && apt-get install -y xvfb libxtst6 libnss3 libatk-bridge2.0-0 libgtk-3-0 libxss1 libasound2
    script:
        - npm ci --cache .npm --prefer-offline
        - echo "Running tests now"
        - export ELECTRON_DISABLE_SANDBOX=1
        - xvfb-run npm test

package.json

  "scripts": {
    "test": "npm run lint && jest --config ./src/lib-code/jest.config.js",
    "lint": "eslint src/lib-code"
  },
  "devDependencies": {
    "electron": "^9.2.1",
    "jest": "^26.4.0"
  },

Docker image used: node:latest

Output

Fontconfig warning: "/etc/fonts/fonts.conf", line 100: unknown element "blank"
[1071:0819/190428.116634:FATAL:gpu_data_manager_impl_private.cc(439)] GPU process isn't usable. Goodbye.

To solve this I probably need to pass the --disable-gpu flag to electron, but I can't find a way to do it currently. Also, I have read elsewhere that running electron on Gitlab requires the --disable-dev-shm-usage flag but I don't think there is way to pass that parameter currently.

Test suit fails to run outputs undefined

running the command yarn test inside the electron project shows this error. I am not able to conclude anything from the output.
runnerErr
This is the test file which is failing
firstTest

Electron fails to find app with Yarn v2 & pnp

I'll try to see if I can publish a repo with a simple reproduction... but as the title says, I get failures when the runner launches Electron that indicate the app could not be found inside a project using Yarn v2 (pnp).

I unplugged the runner and modified the child process spawn from process.execPath to yarn with the first argument being node (so... yarn node ...). That got further, and Electron started. However, it then failed trying to import from the @jest-runner/rpc package.

It would be great if this runner could support Yarn v2.

[Feature]: Fake Timers

It looks like fake timers have been purposefully turned off. Would it be possible to implement fake timers?

Problem running inside Docker

Hello all, I am trying to run the tests inside a docker container, following the steps, using the following configuration:

FROM node:14

RUN apt-get update -y && apt-get install -y xvfb
ENV DISPLAY=':99'
RUN Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
RUN npm test

However, the tests hang, with no error message at all, I can't even get a clue on what's going on:

npm test

> [email protected] test /app
> jest "--selectProjects" "e2e" "--verbose"

Running one project: e2e

Test Suites: 0 of 5 total
Tests:       0 total
Snapshots:   0 total
Time:        422 s

Any hint on what's going on?

renderer console not work

Thanks for this great runner first, it make to test web component with jest possible.
I am new to electron, may be it is something basic I don't know.
How to make the renderer process to output to terminal?
I tried process.stdout.write and remote.getGlobal().console, but all not work.

Spawns multiple processes when using --watch

Hi, first off thanks for this package. Solves many issues for me.

I have one issue tho. When running using --watch, I get multiple electron processes on each change. I was able to solve it by running cleanup after all tests, and it doesn't seem to cause any other issues or run differently.

I just removed this conditional.

Not sure if I'm missing something, or if this even merits a pull request. But I'd be happy to contribute with whatever you suggest.

Running in Bitbucket pipeline: --no-sandbox

I am trying to run test through out pipeline in Bitbucket. I keep hitting this error:

[973:1011/205026.940590:FATAL:atom_main_delegate.cc(210)] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.

Is there a way to pass the --no-sandbox flag through? Or use a user other than root? Or maybe some other solution?

I tried this: adduser temp && adduser temp sudo && su - temp && yarn test
but I am the first to admit I am not a Systems person.

-- Update:
I am passed that one, but am now hitting an error that says (electron:987): Gtk-WARNING **: cannot open display: that I can't seem to get around.

-- another update:
I am passed that one, and am now hitting xhost: unable to open display ":0.0" :sigh:

Allow disabling hardware acceleration

I have some unit tests which compares the content of a Canvas with a PNG containing the expected output. Unfortunately tests like these are not deterministic because of hardware acceleration. My workstation supports hardware acceleration but my CI system does not. So the output is slightly different and therefor tests are failing because the actual canvas doesn't match the expected output.

This can be fixed by disabling hardware acceleration but unfortunately there is no such option in jest-electron-runner yet. I guess the easiest way would be implementing an environment variable like JEST_ELECTRON_RUNNER_DISABLE_HARDWARE_ACCELERATION.

Or maybe it is a good idea to disable hardware acceleration by default and let users enable it on demand with an environment variable like JEST_ELECTRON_RUNNER_ENABLE_HARDWARE_ACCELERATION?

Make it possible to show: true electron

I have tests that use advanced browser API (svg) so I find jest-electron-runner essential to run my tests. However, I would like to be able to occasionally inspect how the results look like.

I actually have two problems/questions:

  1. I would like to add a configuration option to show: true the electron window on demand -- would you guys be fine if I added a cosmiconfig that would make it possible?
  2. I can't make https://github.com/americanexpress/jest-image-snapshot work -- in particular, I can't figure out how to create screenshots. I suppose that electron's capturePage doesn't work when the window is show: false but I haven't verified this theory yet. Did you guys have any experience with it?

Thanks!

Specifying a different version of Electron (i.e. Electron 3.0.6)

Thanks for the time you took to make this helpful module public.

Is there an easy way to configure this module to use a different version of Electron? I just upgrade from Electron 2 to Electron 3 and my test broke. I use node-sqlite3, a native module that places a file at node_modules/sqlite3/lib/binding/electron-v3.0-darwin-x64/node_sqlite3.node. When my test run, they're running from the Electron 2 environment, so they go looking for the path node_modules/sqlite3/lib/binding/electron-v2.0-darwin-x64/node_sqlite3.node, which is no longer in my project.

I hacked the Electron version in package.json in my project's node_modules, but I'm wondering if there's a better way to configure this.

Thanks again.

Doesn't pass through the 'globals' config.

Variables set using the globals config aren't available when using this runner.

Is there a different approach people should be using to enable this scenario?

jest.config.js

module.exports = {
    globals: {
        __DEV__: true
    },
    runner: "@jest-runner/electron",
    testEnvironment: "@jest-runner/electron/environment",
    ...
}

Works with standard runner, error when using this one: ReferenceError: __DEV__ is not defined

does this work with babel-jest?

I'm using the babel-jest transformer and all I'm getting is my imports in a test being undefined.

FWIW everything is fine if I don't use jest-electron-runner (except I have to mock every the whole of electron).

Sorry in advance if this is a silly question. Just out of ideas.

How to suppress `Download the React DevTools` warnings?

ReactDOM console.infos some messages like "Download the React DevTools" that are normally suppressed when running in node with the user agent check. However, running tests in electron has the chrome user-agent and those are still printed.

Apparently, it can also be suppressed with https://github.com/facebook/react/pull/11448 but I can't make it work with babel-jest to inject it early enough.

Did you guys run into this problem and have a quick workaround? I admit this question not related to this project very directly.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.