Async setup of environment with Jest

倖福魔咒の 提交于 2019-12-12 10:57:53

问题


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 global environment / context for each test ?

I tried it with globalSetup config option:

const auth = require('./src/auth')
const ctx = require('./src/context')

module.exports = () => {
    return new Promise(res => {
        auth.getToken()
            .then(token => {
                ctx.init({token})
                global.token = token
                res()
            })

    })
}

context.js

let _token

const init = ({token}) => {
    _token = token
}

const getToken = () => {
    return _token
}

module.exports = {
    init,
    getToken

}

But both global.token nor ctx.getToken() return undefined.

I need to use helper script and to pass token as env var which is then set as global.

  "scripts": {
    "test": "TOKEN=$(node src/get-token.js) jest"
  },

Is there a better approach (which does not involve shell) ?


回答1:


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;
});


来源:https://stackoverflow.com/questions/48508847/async-setup-of-environment-with-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!