nodejs / node

Node.js JavaScript runtime ✨🐢🚀✨
https://nodejs.org
Other
104.27k stars 28.05k forks source link

test runner runs beforeEach or test case before "before hook" finished #52764

Closed ert78gb closed 1 week ago

ert78gb commented 2 weeks ago

Version

v22.0.0

Platform

Darwin Kernel Version 23.4.0

Subsystem

test_runner

What steps will reproduce the bug?

run the following code with node 22.0.0.

import assert from "node:assert/strict";
import test from "node:test";
import { setTimeout } from "node:timers/promises";

await test("test suite", async (t) => {
  t.before(async () => {
    console.log("before start");
    await setTimeout(100);
    console.log("before end");
  });

  t.beforeEach(async () => {
    console.log("beforeEach start");
    await setTimeout(100);
    console.log("beforeEach end");
  });

  t.afterEach(async () => {
    console.log("afterEach start");
    await setTimeout(100);
    console.log("afterEach end");
  });

  t.after(async () => {
    console.log("after start");
    await setTimeout(100);
    console.log("after end");
  });

  await t.test("test case", async () => {
    console.log("test case start");
    await setTimeout(100);
    assert.ok(true);
    console.log("test case end");
  });
});

the expected output is

before start
before end
beforeEach start
beforeEach end
test case start
test case end
afterEach start
afterEach end
after start
after end

instead of

before start
beforeEach start << "beforEach" strarts before "before end"
before end
beforeEach end
test case start
test case end
afterEach start
afterEach end
after start
after end

If the hooks are not async then the order is correct.

In earlier node version the await keyword helped before the hooks but in node 22.0.0 it doesn't work.

How often does it reproduce? Is there a required condition?

always

What is the expected behavior? Why is that the expected behavior?

the expected console log is

before start
before end
beforeEach start
beforeEach end
test case start
test case end
afterEach start
afterEach end
after start
after end

What do you see instead?

before start
beforeEach start << "beforEach" strarts before "before end"
before end
beforeEach end
test case start
test case end
afterEach start
afterEach end
after start
after end

Additional information

if you need git repo https://github.com/ert78gb/node-22-test-runner-async-hooks

MoLow commented 2 weeks ago

thanks for the great reproduction. I have opened a PR with a fix

ert78gb commented 2 weeks ago

thx for the quick fix