I'm looking for a way to run some common code across tests in multiple spec files in Playwright typescript. My particular case is wanting to upload test results based on testInfo
. I'm aware that fixtures can be used for this, but this is not ideal. With fixtures, I need to specify the fixture for every test, and in my case I don't need to reference the fixture within my tests. This makes it easy to not include the fixture on new tests, and accidentally remove it with lint clean up on existing tests.
I have seen that importing files that include beforeAll
or afterAll
will run that code as expected. But doing the same with beforeEach
or afterEach
only runs that code once, instead of once for each test.
Is there a way to get functionality like beforeEach
or afterEach
for multiple spec files without having to add superfluous code to each test?
The best way I've found to do this is to have common file that you import into each test file and call. This works well for
beforeEach
andafterEach
. However,beforeAll
andafterAll
applies to each spec file. So each will be called once for each spec file, and not for the whole group. If you want those to run once for the whole set of specs a better option is usingglobalSetup
andglobalTeardown
.Common file:
A spec file:
Alternatively, you could also have a set of shared functions that you call in each specs
beforeEach
andafterEach
. But I like the above a little better as it's very obvious if you're missing the common hooks.There is a feature request written. So hopefully there will be a better solution. Note, the solution in the second post appears to work, but fails if the number of workers is 1. Both the
*All
and*Each
hooks will only run for the first spec run.