web icon indicating copy to clipboard operation
web copied to clipboard

Please document how to use global hooks (e.g. beforeEach & afterEach) or pass any other mocha options

Open cbxp opened this issue 3 years ago • 1 comments

It was pretty difficult to find from the code, but you can override mocha config using these methods:

  1. Add testFramework: { config: { /* mocha options here */ } } to web-test-runner.config.js, the contents of testFramework.config will be JSON-serialized to the browser as window.__WTR_CONFIG__.testFrameworkConfig. Unfortuantely, this will not work for hooks, as hook functions are lost during JSON.serialize()
  2. Load a separate .js file in the browser before all tests, e.g.
  testRunnerHtml: testFramework =>
    `<html>
      <body>
        <script type="module" src="/_dist_/ui/setup-tests.js"></script>
        <script type="module" src="${testFramework}"></script>
      </body>
    </html>`

Then, in setup-tests.js you can do the following:

window['__WTR_CONFIG__'].testFrameworkConfig = {
  rootHooks: {    
    afterEach: () => sinon.restore()
  }
}

And you can also put any other before-initialization stuff, e.g. add any mocha/sinon/chai plugins.

cbxp avatar May 19 '21 13:05 cbxp

I have the same problem. when i add { config: { require: './test/hooks.js' } } to the testFramework and run test command line, the terminal is pending on Running tests....

chapery avatar Sep 27 '23 02:09 chapery