0
0

More than 3 years have passed since last update.

Jest の beforeEach() / test() と Promise と setTimeout() の関係

Posted at

要約

  • beforeEach() は常に Promise が (then() まで含め) 全部満たされてから test() に移る。
  • setTimeout() は呼ばれない。

実行例

test.js
describe('async test', () => {
  let called;

  function promise() {
    console.log(called = 'function');

    setTimeout(() => {
      console.log(called = 'setTimeout()');
    }, 0);

    return new Promise(resolve => {
      console.log(called = 'Promise()');
      resolve();
    }).then(() => {
      console.log(called = 'then()');
    });
  }

  describe('test() only', () => {
    test('without await', () => {
      promise();
      expect(called).toBe('Promise()');
    });
  });

  describe('test() only', () => {
    test('with await', async () => {
      await promise();
      expect(called).toBe('then()');
    });
  });

  describe('beforeEach() and test()', () => {
    beforeEach(() => {
      promise();
    });

    test('without await', () => {
      expect(called).toBe('then()');
    });
  });

  describe('beforeEach() and test()', () => {
    beforeEach(async () => {
      await promise();
    });

    test('with await', () => {
      expect(called).toBe('then()');
    });
  });
});
yarn run v1.22.10
$ jest --verbose
 PASS  ./test.js
  async test
    test() only
      ✓ without await (12 ms)
      ✓ with await (2 ms)
    beforeEach() and test()
      ✓ without await (1 ms)
      ✓ with await (7 ms)

  console.log
    function

      at promise (test.js:5:13)

  console.log
    Promise()

      at Promise.then.console.log.called (test.js:12:15)

  console.log
    then()

      at test.js:15:15

  console.log
    function

      at promise (test.js:5:13)

  console.log
    Promise()

      at Promise.then.console.log.called (test.js:12:15)

  console.log
    then()

      at test.js:15:15

  console.log
    function

      at promise (test.js:5:13)

  console.log
    Promise()

      at Promise.then.console.log.called (test.js:12:15)

  console.log
    then()

      at test.js:15:15

  console.log
    function

      at promise (test.js:5:13)

  console.log
    Promise()

      at Promise.then.console.log.called (test.js:12:15)

  console.log
    then()

      at test.js:15:15

Test Suites: 1 passed, 1 total
Tests:       4 passed, 4 total
Snapshots:   0 total
Time:        0.979 s, estimated 1 s
Ran all test suites.
✨  Done in 1.83s.

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0