UNPKG

playwright-fluent

Version:
86 lines (85 loc) 3.44 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const path = tslib_1.__importStar(require("path")); const fs_1 = require("fs"); const playwright_1 = require("playwright"); const simple_fake_server_1 = require("simple-fake-server"); const SUT = tslib_1.__importStar(require("../index")); const record_requests_to_1 = require("../../record-requests-to"); const utils_1 = require("../../../../utils"); describe('on request to respond with', () => { let browser = undefined; let fakeServer = undefined; beforeAll(() => { fakeServer = new simple_fake_server_1.FakeServer(1236); fakeServer.start(); //The FakeServer now listens on http://localhost:1236 }); afterAll(() => { if (fakeServer) { fakeServer.stop(); } }); // eslint-disable-next-line @typescript-eslint/no-empty-function beforeEach(() => { }); afterEach(async () => { if (browser) { await browser.close(); } }); test('should mock response', async () => { // Given browser = await playwright_1.chromium.launch({ headless: true, }); const context = await browser.newContext({ viewport: null }); const page = await context.newPage(); const responseBody = { prop1: 'foobar', }; const mockResponseBody = { prop1: 'mock-foobar', }; const responseHeaders = { 'foo-header': 'bar', }; fakeServer && // prettier-ignore fakeServer.http .get() .to('/foobar') .willReturn(responseBody, 200, responseHeaders); const htmlContent = (0, fs_1.readFileSync)(`${path.join(__dirname, 'on-request-to-respond-with.test.html')}`); fakeServer && // prettier-ignore fakeServer.http .get() .to('/app') .willReturn(htmlContent.toString(), 200); const requests = []; const takeAllPredicate = () => false; const callback = (request) => requests.push(request); await (0, record_requests_to_1.recordRequestsTo)('/foobar', takeAllPredicate, page, callback); // When await SUT.onRequestToRespondWith('/foobar', { method: 'GET', bypassPredicate: () => false }, { headers: responseHeaders, body: mockResponseBody, }, page); await page.goto('http://localhost:1236/app'); await (0, utils_1.sleep)(3000); // Then expect(requests.length).toBe(1); const stringifiedRequest = await (0, utils_1.stringifyRequest)(requests[0]); const request = JSON.parse(stringifiedRequest); expect(request.url).toContain('?foo=bar'); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion expect(request.response.status).toBe(200); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion expect(request.response.payload).not.toMatchObject(responseBody); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion expect(request.response.payload).toMatchObject(mockResponseBody); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion expect(request.response.headers['foo-header']).toBe('bar'); }); });