Closed mattoni closed 1 month ago
Once you create a Server
instance the window.WebSocket
object has been mocked by default. Usually the best place for it is beforeEach
hook.
If it's not working for you it's better to check the documentation of the library. https://playwright.dev/docs/mock#creating-mocks
For example you can try mocking it manually like this:
import { WebSocket } from 'mock-socket';
test.beforeEach(async ({ page }) => {
await page.addInitScript(() => {
window.WebSocket = WebSocket;
});
});
and create a server with mock: false
option later:
test('...', async ({ page }) => {
const server = new Server('ws://localhost:8080', { mock: false });
});
Hey @Atrue thanks for the response. The issue I had was the WebSocket definition doesn't get passed through the addInitScript(), so the definition is never overwritten. Is there a workaround for that you're aware of? It looks like the stuff in the init script is completely isolated.
You need to try the examples in the documentation and make sure they works, if so you can try mocking the WebSocket the same way, you can even try it without this library, but there is no difference.
As mocking getBattery
is the same as the mocking WebSocket
it should work in both cases. But if the playwright has difference there you can also try using Object.defineProperty
import { WebSocket } from 'mock-socket'; test.beforeEach(async ({ page }) => { await page.addInitScript(() => { window.WebSocket = WebSocket; }); });
and create a server with
mock: false
option later:test('...', async ({ page }) => { const server = new Server('ws://localhost:8080', { mock: false }); });
With this, I have the following error in the console:
Uncaught ReferenceError: _mockSocket is not defined
What am I missing?
Looks like the Playwright’s addInitScript
only accepts serializable functions or objects https://playwright.dev/docs/api/class-browsercontext#browser-context-add-init-script-option-arg
So it means playwrights can’t share the sync context between the test script and the page.
It may be done manually with async context https://playwright.dev/docs/api/class-browsercontext#browser-context-expose-function, but currently mock-socket
can’t help with it.
Currently you can check playwright websocket discussion here https://github.com/microsoft/playwright/issues/4488
Any examples on how to get this set up with Playwright? Having a hard time finding any way to mock websockets there.