Jest run async function ONCE before all tests

2020-05-25 05:03发布

I want to use jest for my server unit testing (instead of mocha+chai). Is there a way I can run async function before all tests start (init purposes) only once and not for every test file? And also if there's a way of running something after all tests are done?

4条回答
smile是对你的礼貌
2楼-- · 2020-05-25 05:32

jest provides option for both global setup and teardown in new versions. You can create files for both setup and teardown exporting an async function and provide that path in jest configurarion like this.

"globalSetup": "setup-file-path",
"globalTeardown": "tear-down-file-path"
查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-05-25 05:40

If you execute jest tests with npm you can run any node command or any executable before executing other command

"scripts": {
    "test": "node setup.js && jest"
  }

so now you can run this with command

$ npm t
查看更多
女痞
4楼-- · 2020-05-25 05:45

This feature was added in Jest's 22 version, with globalSetup and globalTeardown configurations. Look at this for examples.

查看更多
再贱就再见
5楼-- · 2020-05-25 05:48

Jest provides beforeAll and afterAll. As with test/it it will wait for a promise to resolve, if the function returns a promise.

beforeAll(() => {
  return new Promise(resolve => {
    // Asynchronous task
    // ...
    resolve();
  });
});

It also supports callback style, if you have some existing test code that uses callbacks, although it's recommended to use promises.

beforeAll(done => {
  // Asynchronous task
  // ...
  done();
});
查看更多
登录 后发表回答