使用Jest异步设置环境

使用Jest异步设置环境

问题描述:

Jest 中运行e2e测试之前,我需要从服务器获取身份验证令牌。

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 ?

我尝试使用 globalSetup 配置选项:

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

}

但是 global.token ctx .getToken() return undefined。

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

我需要使用帮助脚本并将令牌作为env var传递,然后将其设置为 global

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

有没有更好的方法(不涉及shell)?

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

有一个名为的CLI / config选项: setupFiles ,它在执行测试代码之前立即运行。

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 可能类似于:

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

然后你可以直接在每个测试套件(文件)中访问 authToken code> beforeAll(_ => console.log(authToken))// 123 。

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

但是,如果你想要一个每个工作程序(cpu核心)而不是每个测试文件运行的全局设置(默认情况下建议使用,因为测试套件是沙箱)。根据当前的jest API约束,您可以选择通过 testEnvironment 选项。然后你需要实现一个自定义类,扩展 jsdom / node 环境公开 setup / runScript / 拆解 api。

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.

示例:

customEnvironment.js

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

my-test.js

let authToken;

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