Skip to content

Hooks not working when loaded from an external vitest.setup.js file #3403

@nicojs

Description

@nicojs

Describe the bug

Hooks (i.e. beforeEach and friends) do not work as expected when loaded from an 'external' setup file.

The hooks run for the first test file but not the following. For example, when your setup file has this:

import { beforeEach } from "vitest";

console.log('setup loading...');
beforeEach((a) => {
  console.log(`Detected: ${a.meta.file.name}`);
});

Then you only see "Detected: src/math.spec.js" for the first test; it proceeds to the following test files without executing this beforeEach again.

I'm not entirely sure what "external" means here, but whenever a setup file is loaded from an 'externalize' location from vite-node, the problem occurs:
https://github.com/vitest-dev/vitest/blob/6433224c0a05d29968eead273d1c57c680034566/packages/vite-node/src/client.ts#L278-285

I can reproduce it by putting the vitest.setup.js file inside a sibling directory. Please take a look at the reproduction instructions below.

Reproduction

external-setup.zip

  1. Unzip this file unzip external-setup.zip -d external-setup.
  2. cd external-setup
  3. npm install
  4. cd project
  5. npx vitest run.

You see this output:

 RUN  v0.31.1 /home/nicojs/github/tmp/project

stdout | unknown test
setup external...

stdout | src/math.spec.js > add > should add 40, 2 = 42
From external: src/math.spec.js

 ✓ src/math.spec.js (1)
 ✓ src/min.spec.js (1)

 Test Files  2 passed (2)
      Tests  2 passed (2)
   Start at  23:56:41
   Duration  205ms (transform 21ms, setup 6ms, collect 13ms, tests 2ms, environment 0ms, prepare 55ms)

As you can see, the beforeEach hook is only executed for math.spec.js, not min.spec.js.

System Info

System:
    OS: Linux 5.15 Ubuntu 20.04.5 LTS (Focal Fossa)
    CPU: (16) x64 11th Gen Intel(R) Core(TM) i7-11850H @ 2.50GHz
    Memory: 13.05 GB / 15.49 GB
    Container: Yes
    Shell: 5.0.17 - /bin/bash
  Binaries:
    Node: 18.12.1 - ~/.nvm/versions/node/v18.12.1/bin/node
    Yarn: 1.22.19 - ~/.nvm/versions/node/v18.12.1/bin/yarn
    npm: 8.19.2 - ~/.nvm/versions/node/v18.12.1/bin/npm
  Browsers:
    Chrome: 110.0.5481.77

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    p3-minor-bugAn edge case that only affects very specific usage (priority)pr welcome

    Type

    No type

    Projects

    Status

    Approved

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions