vitest-dev / vitest

Next generation testing framework powered by Vite.
https://vitest.dev
MIT License
13.08k stars 1.17k forks source link

Run Browser Mode tests in a Node.js context #6668

Closed mrmckeb closed 1 month ago

mrmckeb commented 1 month ago

Clear and concise description of the problem

First, Browser Mode is a great addition.

We've been using it for a while now and we've hit situations a few times where we've imported things into our tests that are not able to run in a browser context.

This allows things like using Node.js APIs (i.e. reading/writing to disk).

Suggested solution

Browser Mode runs only tested code in a browser, akin to Playwright's Components feature.

I realise this would mean that libraries like Testing Library would need additional logic/wrappers to work with this mode.

Alternative

No response

Additional context

No response

Validations

hi-ogawa commented 1 month ago

We've been using it for a while now and we've hit situations a few times where we've imported things into our tests that are not able to run in a browser context.

This allows things like using Node.js APIs (i.e. reading/writing to disk).

Can you be more specific about your use case? For reading a file, you might be able to mock node:fs with server commands https://vitest.dev/guide/browser/commands.html#files-handling

sheremet-va commented 1 month ago

The execution model is intentionally different from playwright and more like traditional test runners where the whole file is imported in the browser. This also makes migrating old tests easier because you don't need to rewrite them.

If you need access to Node.js APIs, you can create a command to communicate between the browser and the server: https://vitest.dev/guide/browser/commands.html

mrmckeb commented 1 month ago

Thanks for sharing that, I had completely missed that there were commands for some Node.js APIs.

For more context, we had hit a few issues where our engineers expected behaviour more akin to Playwright, including getting access to the page object. https://vitest.dev/guide/browser/context.html#page

I think commands gets us by for now @sheremet-va and @hi-ogawa, and we can rewrite some of our utils to be browser compatible.

sheremet-va commented 1 month ago

For more context, we had hit a few issues where our engineers expected behaviour more akin to Playwright, including getting access to the page object.

Good thing the documentation states that it is not the case 😄

I've been thinking about exposing the Vitest page, userEvent and commands APIs on the test context, but since they are not actually scoped to the test it might be confusing for people 🤔

it('some test', async ({ page, userEvent }) => {
  // test uses both page and userEvent
})
mrmckeb commented 1 month ago

Thanks! I agree that as they're not scoped and work differently than someone might expect (even if the docs explain the differences), it could be confusing...