Code Monkey home page Code Monkey logo

playwright-test's Introduction

playwright-test NPM Version NPM Downloads NPM License tests

Run mocha, zora, uvu, tape and benchmark.js scripts inside real browsers with playwright.

Install

pnpm install playwright-test

Usage

playwright-test [files] [options]
# or
pw-test [files] [options]

Options

Description
    Run mocha, zora, uvu, tape and benchmark.js scripts inside real browsers with `playwright` and in Node.

  Usage
    $ playwright-test [files] [options]

  Options
    -r, --runner       Test runner. Options: mocha, tape, zora, uvu, none, taps and benchmark. Internal runners are autodetected by default. It also accepts a path to a module or a module ID that exports a `playwrightTestRunner` object.
    -b, --browser      Browser to run tests. Options: chromium, firefox, webkit.  (default chromium)
    -m, --mode         Run mode. Options: main, worker and node.  (default main)
    -d, --debug        Debug mode, keeps browser window open.  (default false)
    -w, --watch        Watch files for changes and re-run tests.
    -i, --incognito    Use incognito window to run tests.  (default false)
    -e, --extension    Use extension background_page to run tests.  (default false)
    --cov              Enable code coverage in istanbul format. Outputs '.nyc_output/coverage-pw.json'.  (default false)
    --report-dir       Where to output code coverage in instanbul format.  (default .nyc_output)
    --before           Path to a script to be loaded on a separate tab before the main script.
    --sw               Path to a script to be loaded in a service worker.
    --assets           Folder with assets to be served by the http server.  (default process.cwd())
    --cwd              Current directory.  (default /Users/hd/code/playwright-test)
    --extensions       File extensions allowed in the bundle.  (default js,cjs,mjs,ts,tsx)
    --config           Path to the config file
    -v, --version      Displays current version
    -h, --help         Displays this message


  Examples
    $ playwright-test test.js --runner tape
    $ playwright-test test --debug
    $ playwright-test "test/**/*.spec.js" --browser webkit --mode worker --incognito --debug

    $ playwright-test bench.js --runner benchmark
    # Uses benchmark.js to run your benchmark see playwright-test/mocks/benchmark.js for an example.

    $ playwright-test test --cov && npx nyc report --reporter=html
    # Enable code coverage in istanbul format which can be used by nyc.

    $ playwright-test "test/**/*.spec.js" --debug --before ./mocks/before.js
    # Run a script in a separate tab. Check ./mocks/before.js for an example.
    # Important: You need to call `self.PW_TEST.beforeEnd()` to start the main script.

  Runner Options
    All arguments passed to the cli not listed above will be fowarded to the runner.
    $ playwright-test test.js --runner mocha --bail --grep 'should fail'

    To send a `false` flag use --no-bail.
    Check https://mochajs.org/api/mocha for `mocha` options or `npx mocha --help`.

  Notes
    DEBUG env var filtering for 'debug' package logging will work as expected.
    $ DEBUG:app playwright-test test.js

    Do not let your shell expand globs, always wrap them.
    $ playwright-test "test/**" GOOD
    $ playwright-test test/** BAD

Client

This client package exposes the playwright-test options and some Playwright browser context methods to be used in tests.

import * as Client from 'playwright-test/client'

it('should setoffline', async () => {
  if (Client.mode === 'main' && Client.options.extension === false) {
    globalThis.addEventListener('offline', () => {
      console.log('offlineee')
    })
    await Client.context.setOffline(true)
    equal(navigator.onLine, false)
    await Client.context.setOffline(false)
    equal(navigator.onLine, true)
  }
})

it('should geolocation', async () => {
  if (Client.mode === 'main') {
    const deferred = pdefer()
    await Client.context.setGeolocation({
      latitude: 59.95,
      longitude: 30.316_67,
    })
    await Client.context.grantPermissions(['geolocation'])

    navigator.geolocation.getCurrentPosition((position) => {
      deferred.resolve(position)
    })

    const position = (await deferred.promise) as GeolocationPosition
    equal(position.coords.latitude, 59.95)
  }
})

Flow control

All test runners support automatic flow control, which means you don't need to call special function or trigger any event in your tests to stop the run. The none runner does not support flow control.

To manually stop the run you can use process.exit:

process.exit(0) // stops the run and exits with success
process.exit(1) // stops the run and exits with failure

Custom test runner

You can define a custom test runner by passing a path to a file or a node module id that exports an object called playwrightTestRunner that implements the TestRunner interface.

$ playwright-test test.js --runner ./my-runner.js
# or
$ playwright-test test.js --runner my-runner

You can also just define you test runner in the config file.

// playwright-test.config.js
/** @type {import('../src/runner.js').RunnerOptions} */
const config = {
  testRunner: {
    compileRuntime: (options, paths) => {
      return `
import mocha from 'mocha/mocha.js'
mocha.setup({
    reporter: 'spec',
    timeout: 5000,
    ui: 'bdd',
})

${paths.map((url) => `await import('${url}')`).join('\n')}

  mocha
    .run((f) =>{
      process.exit(f)
    })
        `
    },
  },
}

export default config
export interface TestRunner {
  /**
   * Module ID name used to import the test runner runtime.
   * Used in auto detection of the test runner.
   */
  moduleId: string
  /**
   * Options made available to the compiled runtime.
   * This is useful to pass options to the test runner.
   *
   * @example
   * ```js
   * const options = JSON.parse(process.env.PW_OPTIONS)
   * const testRunnerOptions = options.testRunner.options
   * ```
   */
  options?: unknown
  /**
   * Esbuild config for the test runner
   */
  buildConfig?: BuildOptions
  /**
   * Compile runtime entry point for esbuild
   *
   * @param options - Runner options
   * @param testPaths - Test paths
   * @returns
   */
  compileRuntime: (options: RunnerOptions, testPaths: string[]) => string
}

Config

The config file needs to be commonjs for now, so if your package is pure ESM you need to use .cjs extension.

Configuration can be done with cli flags or config files.

package.json, // using property `pw-test` or `playwright-test`
.playwright-testrc.json,
.playwright-testrc.js,
.playwright-testrc.cjs,
playwright-test.config.js,
playwright-test.config.cjs,
.pw-testrc.json,
.pw-testrc.js,
.pw-testrc.cjs,
pw-test.config.js,
pw-test.config.cjs,
.config/playwright-testrc.json
.config/playwright-testrc.js
.config/playwright-testrc.cjs
.config/pw-testrc.json
.config/pw-testrc.js
.config/pw-testrc.cjs

The config type can be imported from the entrypoint.

/** @type {import('playwright-test').RunnerOptions} */
const config = {
  // ...
}

export default config

The config file can also export a function that receives the cli options as argument.

/** @type {import('playwright-test').ConfigFn} */
function buildConfig(cliOptions) {
  return {
    buildConfig: {
      bundle: cliOptions.mode !== 'node',
    },
  }
}

export default buildConfig

Interface

export interface RunnerOptions {
  input?: string[]
  testRunner: TestRunner
  cwd: string
  extensions: string
  browser: 'chromium' | 'firefox' | 'webkit'
  debug: boolean
  mode: 'main' | 'worker' | 'node'
  incognito: boolean
  extension: boolean
  assets: string
  before?: string
  sw?: string
  cov: boolean
  reportDir: string
  buildConfig: BuildOptions
  buildSWConfig: BuildOptions
  browserContextOptions?: BrowserContextOptions
  beforeTests: (opts: RunnerOptions) => Promise<unknown>
  afterTests: (
    opts: RunnerOptions,
    beforeTestsOutput: unknown
  ) => Promise<unknown>
}

Run in CI

Check our CI config .github/workflows/main.yml and the playwright Github Action

License

MIT © Hugo Dias

playwright-test's People

Contributors

achingbrain avatar dependabot-preview[bot] avatar dependabot[bot] avatar gamtiq avatar github-actions[bot] avatar gozala avatar hugomrdias avatar marcopolo avatar paperstrike avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

playwright-test's Issues

ssss

hhh

### Tasks
- [ ] Draft task

Update playwright-core version to support Ubuntu 22.04

GitHub actions are updating their ubuntu-latest image to Ubuntu 22.04 (announcement).

It appears that playwright-test currently depends on playwright-core version 1.22.1 (source).

However, it looks like playwright only supports Ubuntu 22.04 as of Playwright 1.25.0 (release).

As a result, attempting to install playwright using npx playwright install --with-deps in a GitHub action workflow based on ubuntu-latest will fail since it will attempt to use the playwright version from playwright-test.

Errors such as the following:

Get:27 https://packages.microsoft.com/ubuntu/22.04/prod jammy/main amd64 Packages [57.8 kB]
Fetched 4470 kB in 1s (3728 kB/s)
Reading package lists...
Reading package lists...
Building dependency tree...
Reading state information...
Package ttf-ubuntu-font-family is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

Package ttf-unifont is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
However the following packages replace it:
  fonts-unifont

Package libicu66 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

Once can force the playwright version to install to 1.28.0 using npx playwright@^1.28.0 install --with-deps and then the playwright install will succeed, but webkit tests will fail since playwright-test will download Webkit 15.4 (since that is the version used by playwright-core 1.22.1) and discover it is missing some dependencies.

Any chance playwright-test could update the playwright-core version to 1.28.0 (or make it a peer dependency / not pin the version?)

Update to 1.35 playwright-core possible?

Thank you for your nice testing framwork!

I have a pending pull request on my project using it:
fails-components/webtransport#130

However, the test suffered from some severe flackyness.
As it turned out it was caused by segmentation faults in chromium's network service handling webtransport.
The bug was fixed in 115 of chromium, as playwrigth-core was just updated to support this version.
I would like to ask , if it is possible to release a new version with the updated playwrigth-core version 1.35 .
Thanks!

Error: ReferenceError: mocha is not defined

As I was working on achingbrain/it#8 I started seeing following errors coming from playwright-test

npm test
> [email protected] test /Users/gozala/Projects/it/packages/browser-readablestream-to-it
> playwright-test

✔ Browser setup
✔ Bundling tests
'window.webkitStorageInfo' is deprecated. Please use 'navigator.webkitTemporaryStorage' or 'navigator.webkitPersistentStorage' instead.
file:////Users/gozala/Projects/it/node_modules/mocha/mocha.js:25915

 Error: ReferenceError: mocha is not defined
    at eval (file:////Users/gozala/Projects/it/node_modules/playwright-test/src/setup-mocha.js:9:1)
    at Object.../../node_modules/playwright-test/src/setup-mocha.js (http://localhost:3000/bundle.509459cbd52e64d9231b.js:519:1)
    at __webpack_require__ (http://localhost:3000/bundle.509459cbd52e64d9231b.js:20:30)
    at eval (file:///multi%2520/Users/gozala/Projects/it/node_modules/playwright-test/src/setup-mocha.js%2520/Users/gozala/Projects/it/packages/browser-readablestream-to-it/test.js:1:1)
    at Object.0 (http://localhost:3000/bundle.509459cbd52e64d9231b.js:588:1)
    at __webpack_require__ (http://localhost:3000/bundle.509459cbd52e64d9231b.js:20:30)
    at http://localhost:3000/bundle.509459cbd52e64d9231b.js:84:18
    at http://localhost:3000/bundle.509459cbd52e64d9231b.js:87:10
npm ERR! Test failed.  See above for more details.

To check if there was something wrong with my changes or setup I submitted pull with muster and empty commit here
achingbrain/it#10

Which seems to still fail https://travis-ci.org/github/achingbrain/it/jobs/715667645

Not sure what is causing this yet.

Crash when reading JSON file

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at getPw (file:///home/travis/build/ipfs/js-ipfs/node_modules/playwright-test/src/utils/index.js:261:25)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async MochaRunner.launch (file:///home/travis/build/ipfs/js-ipfs/node_modules/playwright-test/src/runner.js:109:16)
    at async MochaRunner.run (file:///home/travis/build/ipfs/js-ipfs/node_modules/playwright-test/src/runner.js:265:23)
Command failed with exit code 1: pw-test **/*.spec.{js,ts} test/browser.{js,ts} --mode main --config /home/travis/build/ipfs/js-ipfs/node_modules/aegir/src/config/pw-test.js --timeout=60000 --bail

ESM Worker support

Is your feature request related to a problem? Please describe.

I'm porting a library to ESM and have a test suite in workers, for it to work I need to be able to pass type: "module" to a worker. module environment will allow to use import.meta.url

Describe the solution you'd like

A --type flag with either classic or module (as in Web API) which will do Worker("${filePath}", { type: "${workerType}" })

Describe alternatives you've considered

Since Worker creation is hardcoded there's no way to pass any options at all

Prevent zora test window from closing on error

Is your feature request related to a problem? Please describe.
I'm using playwright-test to run zora tests. When there is an error, the playwright process exits. I would like it to stay open and try again as code changes.

Describe the solution you'd like
If there were some cli flag to tell the playwright to keep the process running even through errors, that would be great.

Describe alternatives you've considered
Maybe there's a sensible way to run the playwright process with nodemon, though that means that when run in --debug, the browser window will be opening and closing repeatedly.

Thanks for this library, by the way. It's great!

Disable emojis/colour when CI env var is set

CI logging output can be really hard to read:

\x1B[0m\x1B[0m\n'
 \x1B[0m  ping test\x1B[0m\n'
   \x1B[36m  - should listen for ping\x1B[0m\n'

Some CI logging setups handle this well, some do not - the above is a browser test running in a docker image on GitHub CI so I think it's actually Docker which is mangling the output, at any rate it's full of garbage.

It would be better to disable all the fancy formatting when the process.env.CI env var is set. Some runners do this automatically (e.g. mocha) but others don't (playwright?).

Coverage

What's the plan for getting coverage information out of this test runner?

I ran the following but got empty reports:

$ nyc --reporter html --reporter lcov playwright-test

and trying to fit nyc into the --runner value fails with TypeError: object null is not a constructor

Some way to read contents of non-js files

Is your feature request related to a problem? Please describe.

When working with test data sets it is common to encounter them in .csv or some binary format. Unfortunately it is impossible to use such datasets without compiling them into some module ahead of time, which is a significant downside as keeping test up to date with datasets incur extra barriers.

Describe the solution you'd like

Ideally we would have some universal way through import syntax or perhaps via fetch API or maybe even a custom module to load contents of arbitrary files that will work across standard node runtime and playwright tests.

Describe alternatives you've considered

  • Tried using fetch, pasing --extensions csv flag, using fs module but non of them work.
  • generating dummy js files that simply export string of content, this works but is a pain to maintain also things get out of date frequently.

Version 11 no longer runs test files with typescript syntax unless you manually specify the test runner

Describe the bug
After updating from v10.0.1 to v11.0.3 (or just v11.0.0) I can no longer run typescript test files that have any typescript syntax.

To Reproduce
Steps to reproduce the behavior:

  1. Create a test file with typescript syntax (e.g. type annotations)
  2. Run npx playwright-test example.test.ts

Expected behavior
The test runs.

Actual behavior
acorn trips up on the typescript syntax, e.g.

❯ yarn playwright-test src/update.test.ts
yarn run v1.22.19
warning package.json: No license field
$ /home/birtles/jpdict-idb/node_modules/.bin/playwright-test src/update.test.ts
SyntaxError: Unexpected token (61:27)
    at pp$4.raise (file:///home/birtles/jpdict-idb/node_modules/acorn/dist/acorn.mjs:3554:13)
    at pp$9.unexpected (file:///home/birtles/jpdict-idb/node_modules/acorn/dist/acorn.mjs:762:8)
    at pp$8.parseVar (file:///home/birtles/jpdict-idb/node_modules/acorn/dist/acorn.mjs:1313:12)
    at pp$8.parseVarStatement (file:///home/birtles/jpdict-idb/node_modules/acorn/dist/acorn.mjs:1175:8)
    at pp$8.parseStatement (file:///home/birtles/jpdict-idb/node_modules/acorn/dist/acorn.mjs:917:17)
    at pp$8.parseTopLevel (file:///home/birtles/jpdict-idb/node_modules/acorn/dist/acorn.mjs:819:21)
    at Parser.parse (file:///home/birtles/jpdict-idb/node_modules/acorn/dist/acorn.mjs:591:15)
    at Function.parse (file:///home/birtles/jpdict-idb/node_modules/acorn/dist/acorn.mjs:641:35)
    at parse (file:///home/birtles/jpdict-idb/node_modules/acorn/dist/acorn.mjs:5943:17)
    at detectTestRunner (file:///home/birtles/jpdict-idb/node_modules/playwright-test/src/utils/auto-detect.js:11:22) {
  pos: 1203,
  loc: Position { line: 61, column: 27 },
  raisedAt: 1204
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Desktop (please complete the following information):

  • OS: [e.g. iOS] Ubuntu 22.04.2
  • Browser [e.g. chrome, safari] chrome
  • Version [e.g. 22] ? (Not sure what this is asking for. OS version? Browser version?)

Additional context
If I have a .ts file that doesn't happen to use any type annotations etc. it works fine. The position of the error seems to correspond to the first bit of syntax that is not javascript, (e.g. a type annotation).

From what I can tell, it looks like this is due to the test runner auto-detection code. Part of this was added in 10.0.1 (477ec99) but it wasn't actually used until 11.0.0 (1d73a36).

If I specify the test runner explicitly (e.g. -r mocha) it works.

It appears the auto-detection code is attempting to parse the test file using acorn which doesn't support parsing typescript (see acornjs/acorn#1162 (comment)).

It has been suggested elsewhere to use typescript-estree to parse typescript files. (Although the link in that comment is broken, an updated link to typescript-estree is: https://github.com/typescript-eslint/typescript-eslint/tree/main/packages/typescript-estree.)

[feature]: Assets from multiple directories

Is your feature request related to a problem? Please describe.
I am trying to create a Web Worker from a script that lives in a dependency, but in order to server this file I somehow need to make it an asset of the polka server. It seems like I now have to copy it into the root directory of the project I want to test to make it work

Describe the solution you'd like
I would be great if I somehow could bundle and provide it without having to manually copy the the asset to the same folder as cwd. The --assets command does not do what I expect, it seems to just rewrite where the asset folder is.

Describe alternatives you've considered
Make a script that copies the worker scripts into some temp folder that is inside of root folder of the project

Double output on firefox webworkers

All output is repeated twice. Only happens with firefox webworkers. Printing a random number suggests the tests are not being run twice:

> [email protected] test:interface:core
> aegir test -f test/interface-core.js "--bail" "-t" "webworker" "--" "--browser" "firefox"

Test Webworker
✔ Browser setup
✔ Bundling tests
I'm `fs` modules
I'm `fs` modules


  interface-ipfs-core tests
  interface-ipfs-core tests
    .bitswap.stat
    .bitswap.stat
      ✓ should respect timeout option when getting bitswap stats
      ✓ should respect timeout option when getting bitswap stats
      ✓ should get bitswap stats
      ✓ should get bitswap stats
      ✓ should not get bitswap stats when offline (2592ms)
      ✓ should not get bitswap stats when offline (2592ms)
    .bitswap.wantlist
    .bitswap.wantlist
      ✓ should respect timeout option when getting bitswap wantlist
      ✓ should respect timeout option when getting bitswap wantlist
      ✓ should get the wantlist
      ✓ should get the wantlist
      ✓ should not get the wantlist when offline (1905ms)
      ✓ should not get the wantlist when offline (1905ms)
      ✓ should remove blocks from the wantlist when requests are cancelled (112ms)
      ✓ should remove blocks from the wantlist when requests are cancelled (112ms)
      ✓ should keep blocks in the wantlist when only one request is cancelled (1109ms)
      ✓ should keep blocks in the wantlist when only one request is cancelled (1109ms)

autodetect fail with describe.only

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

No coverage data generated in Linux

Describe the bug
The temporary dir generated by tempy in my Linux machine are like /tmp/xxx.
My project is in /home/user/abc.

I can't generate a correct playwright-test coverage data after #288.

To Reproduce
Steps to reproduce the behavior:

  1. Check the depth the temporary dir generated by tempy in your Linux machine.
  2. Put a simple playwright-test project in a folder with a deeper depth.
  3. Run playwright-test to get the coverage data.
  4. The coverage data is empty.

Expected behavior
The coverage data is not empty and is correct.

Screenshots
N/A

Desktop

  • OS: Ubuntu 21.04
  • Browser: Chrome
  • Version: 96

Additional context
My guess: #288 (comment)

Add quiet mode

Is your feature request related to a problem? Please describe.

playwright-test emits messages like [playwright-test] Autodetected "mocha" as the runner.. These messages are great in interactive mode, but can end up in reporting when output redirecting to a file.

For example:

pw-test test/test.js --reporter json --mode node > test/report/node.json

may include an autodetection message in node.json.

Describe the solution you'd like

Add a quiet mode that only emits reporter results.

Describe alternatives you've considered

For the autodetection message, it is possible to explicitly set a runner with -r mocha to avoid the autodetection message.

Support tinybench

It would be great if this supported tinybench - it's like benchmark.js but is maintained and has decent promise support, along with extension points for test setup and teardown.

`util` should be polyfilled for mocha

Describe the bug
mocha uses util and without this it can't be bundled up. Currently no errors in the test cases as the browser-compatible util is listed as a dep of assert and the test cases in this repo run with it.

To Reproduce

git clone ...
git switch -c test-mocha-util
yarn install
yarn remove assert

create a file named example.js, with the following lines:

it('should work', () => {});

run node ./cli.js example.js, and you will see the error.

Mocking timers can cause tests to hang

Describe the bug

NOTE: It's likely this is not something that can/should be fixed in playwright-test but this caught me out and used up all my GitHub actions build minutes overnight so I thought it's worth documenting even if the issue is closed immediately.

It's common to mock timers in unit tests, e.g. using Sinon fake timers.

However, playwright-test waits for the test to end by polling using waitForFunction, passing parameters that means internally waitForFunction uses setTimeout (source).

In some circumstances, these calls to setTimeout can occur while setTimeout is being mocked and in such a way that even when the mocks are restored (e.g. using clock.restore()) the timeout callback that was registered while the mock version was in place is never called.

As described in microsoft/playwright#9123, this is because the code executed by waitForFunction picks up any monkey-patched / mocked globals. It also appears that, as per the above issue, this will not be fixed in playwright itself.

As a result, the call to waitForFunction never resolves and the test suite run simply hangs after completing. In my case, it would hang for 6 hours each time (the GitHub actions default limit it seems).

Possible remediations

  1. Allow specifying which method to use for waitForFunction: 'raf' vs timeout -- this would allow non-extension use cases that don't mock requestAnimationFrame to opt-in to that and continue mocking setTimeout.
  2. Allow specifying a timeout for waitForFunction as a back stop. (This particular timeout appears not to be affected by setTimeout being mocked--either because it is running in a different context or because it is registered before setTimeout is mocked.)
  3. Persuade the playwright maintainers to store references to setTimeout, requestAnimationFrame etc. on page load and use those references in waitForFunction--assuming that is even possible.

For me, I only use setTimeout in a couple of places so I'll likely import it in a way I can mock the import, rather than the global definition, but I'll bet I won't be the last person to hit this issue.

Writing to stdout without console.log imposed line breaks

Is your feature request related to a problem? Please describe.

Test runner I use prints test run progress across several tests on the same line. Running it via playwright-test causes progress to be delimited with \n.

E.g. here is the output from my tests in node

test/variant.spec.js
testMatch ⦿ ⦿ ⦿ ⦿ ⦿ ⦿ ⦿ ⦿ ⦿ ⦿ ⦿ ⦿ ⦿ ⦿ 

When run in playwright output looks like

test/variant.spec.js

testMatch

⦿ 
⦿
⦿
⦿
⦿
⦿
⦿
⦿ 
⦿ 
⦿ 
⦿ 
⦿ 
⦿ 
⦿ 

Describe the solution you'd like
A clear and concise description of what you want to happen.

I would like to get same output when running tests in node and running them in playwright-test

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Considered buffering output and logging it line by line, however that is not ideal because in that case progress is reported far less frequently.

Additional context
Add any other context or screenshots about the feature request here.

I think there are two things that can be done here:

  1. Make test runner interface that iterates over output sending it to the host by other means.
  2. Pollyfill process.stdout and pipe output y mechanism different from console.log

Intermittent failure during test setup

Describe the bug

Sometimes running tests with playwright-test fails with a 404 before the test run starts. Doesn't happen every time, there could be a race condition somewhere.

To Reproduce

Run some tests:

Failed to load resource: the server responded with a status of 404 (Not Found)
http://127.0.0.1:58129/setup.js
✖ Running tests failed.
page.addScriptTag: Error: Failed to load script at http://127.0.0.1:58129/setup.js
    at HTMLScriptElement.script.onerror (eval at evaluate (:3:2389), <anonymous>:8:74)
    at MochaRunner.runTests (file:///path/to/project/node_modules/playwright-test/src/runner.js:231:16)
    at MochaRunner.runTests (file:///path/to/project/node_modules/playwright-test/src/runner-mocha.js:53:44)
    at MochaRunner.run (file:///path/to/project/node_modules/playwright-test/src/runner.js:287:38)
Command failed with exit code 1: pw-test **/*.spec.{js,ts,cjs,mjs} test/browser.{js,ts,cjs,mjs} --mode main --cov --config /path/to/project/node_modules/aegir/src/config/pw-test.js --timeout=60000

Expected behavior

The test suite to start

Desktop (please complete the following information):

Happens on Mac OS X and Linux on CI

Support for vitest

Hi,

I'm currently using vitest (https://vitest.dev) for my unittests and wanted to ask if you might consider supporting this test framework.
It seems that vitest is getting more popular in the Vue/React community.

Thank's a lot!

Support bundling `expect`

Is your feature request related to a problem? Please describe.
I always wanted to write tests with Jest's expect package, while it is not officially supported to do so.

Describe the solution you'd like
It would be GREAT to see expect running in real browser unit tests.

Describe alternatives you've considered
I came across @storybook/expect when looking for a working browser expect, and noticed that it happens by bundling with node-polyfill-webpack-plugin (which has an equivalent @esbuild-plugins/node-globals-polyfill in esbuild) and resolving graceful-fs to fs. (see their repo here)

  • For the bundling, I created a branch third-party-polyfill-inject in my fork. It doesn't have to find which node builtin should be polyfilled in each runner since then.
  • Now the problem comes to the graceful-fs resolution. If you, the author, agrees to directly resolve it to fs, I would be glad to write that in another branch then. And there are other approaches, like making it a cli option, introducing new runners like mocha+expect, etc.

I would like to hear your opinions.

This tool is great, thank you!

Additional context
expect is what the official Playwright Test uses, too. Together with my playwright-fixtures, it is quite funny to see "the offical test runner" supports both e2e and unit tests.

console.time/timeEnd throwing No such label warning

Describe the bug
When running console.time/console.timeEnd, the following warning is reported and I am unable to successfully time tasks:

(node:675331) Warning: No such label 'test: 0.0009765625 ms' for console.timeEnd()

It appears the label that timeEnd expects changes from "label" to "label ms".

I am running playwright-test with mocha tests.

To Reproduce

Create a simple test:

describe('Test', () => {
  it('time/timeEnd', () => {
    console.time('test')
    console.timeEnd('test')
  })
})

Run the test on the cmd line:

./node_modules/.bin/playwright-test test/index.js --runner mocha

Output is:

(node:675331) Warning: No such label 'test: 0.0009765625 ms' for console.timeEnd()
(Use `node --trace-warnings ...` to show where the warning was created)

Expected behavior
Task time should be correctly displayed:

test: 0.08ms

Additional context

  • Playwright v12.6.0

  • Running test in mocha results in correct output

  • Running test using --debug (displaying browser window) and viewing console in browser window shows correct output

  • This problem only occurs in the terminal (I.e. cmd line output).

mocha beforeEach not called

Describe the bug
beforeEach hook of mocha is never called. I'd like to initialize some variables for every test run.

Is this expected? does this work with the other test runners as far as you know?

On github CI this creates `.cache` directory in the package

As it was discovered in multiformats/js-multibase#61 (comment) it appears that running a playwright as github action causes .cache folder to be created in the package root, which then can end up in the npm. For more details here is the configuration of github workflow

https://github.com/Gozala/web-encoding/blob/363310221c17e29fbb67b2cac046272515322164/.github/workflows/node.js.yml#L44-L67

Putting .cache in the .npmignore works around this problem, but ideally that would no be required. At least section in the Readme would be helpful.

Support for `import.meta.url`

Is your feature request related to a problem? Please describe.

I'd like to conditionally load things relative to the test module, which can be achieved as

new URL('./asset.txt', import.meta.url)

However that does not seem to work because import.meta.url is undefined.

Describe the solution you'd like

Have import.meta.url be a module URL as loaded by test runner.

Describe alternatives you've considered

Use of fs.readFile which also does not work

Additional context
Would like test new unixfs importer code across node / browser against a ready dataset

when testing with -r uvu sometimes program never exits

Describe the bug

Running something like playtright-test -r uvu test/web.spec.js sometimes never exits despite the fact that test are finished and output is printed into stdout.

To Reproduce
Here is the case where it kept hanging & I was able to reproduce it locally as well.
https://github.com/web-std/io/pull/2/checks?check_run_id=2560237017

Additional context
After some digging I figured out that problem is caused by the fact that console listener never ran

page.on('console', async (msg) => {
const txt = msg.text()
if (txt.includes(' Total: ')) {
total = Number(txt.replace('Total:', '').trim())
}
if (txt.includes(' Passed: ')) {
passed = Number(strip(txt.replace('Passed:', '').trim()))
await page.evaluate(run(total !== passed))
}
})

As far as I can tell that is because test run was complete sooner than listener was registered. If I make a test await for a single tick things seem to work as expected. Given that output is printed into stdout I wonder if there is a better way to hook into this to make things more reliable.

iframe mode

AFAIK there are two running modes so far:

  • main window
  • worker

It could be interesting to run different test files in different iframes to have sandboxed/isolated environment. An example I have in mind: it would give the ability to have a different customRegistry (for web components) for each test file.

That would probably be less performent and would bring a new set of challenges (synchronising reporting streams, etc) yet I believe it is worth some investigations.

What are your thoughts ?

Prepare service worker without registering it

Is your feature request related to a problem? Please describe.
I want to test a script in a service worker's both presence and absence. However, there are something blocking this:

  1. When using the sw option, playwright-test registers the service worker immediately on the page load.
  2. Unlike workers, service workers can't be terminated.
  3. Unregistering a service worker only take effects after the page unload. There isn't a reliable way to unregister immediately yet. (discuss in w3c/ServiceWorker#614.)
  4. Using a controllable iframe or new window doesn't help, it inherits the service worker.
  5. When not using the sw option, I have to create my own bundle to pass it as an asset to playwright-test.

So there seems no easy way to tun tests in both the service worker's presence and absence.

Describe the solution you'd like

An option, that stops playwright-test from registering the service worker but keeps playwright-test preparing the bundle. Also, the path of the bundled sw should be exposed somewhere (maybe like PW_TEST.env.swURL) so that we can register it later. The user will have more control on the register option, too.

Describe alternatives you've considered

Stop using sw option, and prepare my own bundle for service worker before running playwright-test.

Additional context

None yet.

Update to 1.38 playwright-core possible?

Hi,
again thanks for your testing framework!

I have a pending pull request on my project using it:
fails-components/webtransport#130

It initially suffered from one bug in Chromium, which was fixed afterward, and you were so kind to update your playwright-test and then to use the fixed browser.
Of course, as always I found a second webtransport-related bug in Chromium and I also patched it, it arrived in version 117.
So it would be really nice if you could update to version 1.38 of the playwright-core package.
I hope it will be the last bug in chromium, that is blocking this PR...

Fails to resolve the test runner module

Describe the bug

I was updating libraries that used #548 to currently released playwright, but sadly it seems to fail to resolve the module

playwright-test test --runner entail test/*.js

Error: Cannot resolve module "entail" from "/Users/gozala/Projects/entail"
    at resolveModule (file:///Users/gozala/Projects/entail/node_modules/.pnpm/[email protected]/node_modules/playwright-test/src/utils/index.js:524:11)
    at async resolveTestRunner (file:///Users/gozala/Projects/entail/node_modules/.pnpm/[email protected]/node_modules/playwright-test/src/utils/index.js:544:18)
    at async file:///Users/gozala/Projects/entail/node_modules/.pnpm/[email protected]/node_modules/playwright-test/cli.js:273:34
 ELIFECYCLE  Command failed with exit code 1.

To Reproduce

Execute above command

Expected behavior

I was expecting that module resolution would succeed

Additional context

I am not yet sure why that error is happening, but I suspect that module resolution logic provided in my PR and one that was shipped are different, later failing to account for the context in which resolution takes place.

I will investigate and provide more details as I find them.

Incompatible with mocha 10

Describe the bug
After upgrading to mocha 10, playwright-test fails with:

Error: R] Could not resolve "mocha/mocha-es2018.js"

    node_modules/playwright-test/src/setup-mocha.js:6:18:
      6 │ import mocha from 'mocha/mocha-es2018.js'
        ╵                   ~~~~~~~~~~~~~~~~~~~~~~~

It looks like the mocha-es2018.js artifact was dropped in mochajs/mocha@70fe3ad as part of mochajs/mocha#4848.

I guess we should just use mocha.js but I wonder if there was a reason for using mocha-es2018.js in the first place?

pass environment variables to runtime

Is your feature request related to a problem? Please describe.
In Vite, I can access environment variables (for example, set in .env.development via import.meta.env.

When playwright-test builds my project, I can't access these variables

Describe the solution you'd like
Have a way to pass env variables to code run via playwright-test.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.