Async setup of environment with Jest

后端 未结 3 1211
北恋
北恋 2021-01-04 14:01

Before running e2e tests in Jest I need to get an authentication token from the server.

Is it possible to do this globally one and set it somehow to the glo

3条回答
  •  無奈伤痛
    2021-01-04 14:41

    There's a CLI/config option called: setupFiles, it runs immediately before executing the test code itself.

    "jest": {
      "globals": {
        "__DEV__": true,
        ...
      },
      "setupFiles": [
        "./setup.js"
      ]
    }
    

    setup.js might look something like:

    (async function() {
        // const { authToken } = await fetchAuthTokens()
        global.authToken = '123'
    })()
    

    And then you can access authToken directly in each test suites (files) like beforeAll(_ => console.log(authToken)) // 123.


    However, if you want a global setup that runs per worker(cpu core) instead of per test file (recommended by default since test suites are sandboxed). Based on current jest API constraints, you may choose to customize your test's runtime environment through the testEnvironment option. Then you need to implement a custom class that extends jsdom/node environment exposes setup/runScript/teardown api.

    Example:

    customEnvironment.js

    // my-custom-environment
    const NodeEnvironment = require('jest-environment-node');
    
    class CustomEnvironment extends NodeEnvironment {
      constructor(config) {
        super(config);
      }
    
      async setup() {
        await super.setup();
        const token = await someSetupTasks();
        this.global.authToken = token;
      }
    
      async teardown() {
        await super.teardown();
        await someTeardownTasks();
      }
    
      runScript(script) {
        return super.runScript(script);
      }
    }
    

    my-test.js

    let authToken;
    
    beforeAll(() => {
      authToken = global.authToken;
    });
    

提交回复
热议问题