API mocking
- Install
mswand@msw/playwrightdependencies. - Head to
tests/text-extend.tsand in theFixturesinterface, describe a new fixture callednetwork. Use the type from the@msw/playwrightpackage to annotate it. - Implement the
networkfixture. UsedefineNetworkFixture()from the package, provide it with the handlers and the browsercontext. Start, use, and stop, awaited. Then, set{ auto: true }because I want for API mocking to always be applied, even if this fixture isn't explicitly used in a test. - To make this fixture more flexible, I will create an option fixture called
handlers. Annotate it asArray<AnyHandler>, then implement it as[[], { option: true }]. This way, individual tests and even entire test projects can define their own list of request handlers to affect the network.
- Now, let's use
networkin the test. Reference it and usenetwork.use()to apply request handlers for the Google API requests I want to intercept. - Respond with a mocked response (use the
HttpResponsehelper frommsw).