Issue
Currently, I’m transitioning from CasperJS to using Jest along with Puppeteer. Everything works well when the tests are all within a single file:
beforeAll(async () => {
// obtain `page` and `browser` objects from puppeteer
});
describe('Unit Test A', () => {
// test implementation
});
describe('Unit Test B', () => {
// test implementation
});
afterAll(async () => {
// terminate the browser
});
However, I would prefer not to keep all tests in one file, as it becomes complicated to manage and challenging to execute individual tests, such as only ‘Unit Test A’.
My Attempts
I reviewed Jest’s documentation and discovered the concept of using a setupFiles
option. While this sounds ideal, it executes before each test file, and I would prefer to initialize Puppeteer only once to avoid lengthy setup times. My goal is to reuse the same browser instance across various test files without incurring the setup cost each time.
I considered this approach:
// setting up puppeteer
await require('./unitTestA')(page, browser, config);
await require('./unitTestB')(page, browser, config);
// cleanup operations
This method successfully maintains modularity and reuses the browser instance; however, it prevents me from running the tests independently.
Ultimately, I came across the option to establish a custom Jest testEnvironment
. This is promising, yet the documentation is lacking, leaving me unsure whether a new environment instance is established for each test file or maintained throughout the Jest execution. Furthermore, the API stability is compromised as there is no dedicated setup
method for Puppeteer initialization—all setup must occur in a non-async constructor.
Reason for Inquiry
As I’m still acclimating to Jest, I might be overlooking something fundamental. Before delving deeper, I wanted to ask for insights here.