A module to mock a Playwright or Puppeteer page's goto method.
You have a Playwright or Puppeteer script that you would like to test, but you do not want actual webpages to be loaded every time your tests are ran. This module offers you a concise way to test your script against local copies of the HTML files instead of real webpages.
npm install --save-dev mock-goto
In your tests, call mock-goto before calling the script that you want to test. It is a function that takes 2 arguments:
- The Playwright/Puppeteer Page object the script is using
- A config object (described below)
paths: Required. An object that tells mock-goto how it should mock the goto function. The keys are the links that are going to be visited by the script as found in the source code of the webpage. The values are the paths to the local HTML files with which the webpages will be stubbed.
throwIfNotMapped: Optional. A boolean that tells mock-goto to throw an error if your script is trying to visit a page that is not specified in your paths object. Defaults to false.
After testing, restore the normal behavior of the goto function to avoid any weird results in other tests.
See the runnable examples in examples/. Run them with:
npm run test:examples
import { chromium } from 'playwright';
import mockGoto from 'mock-goto';
import myScript from './index';
describe('My script', () => {
it('Should return an array of trucks and for each, a list of engines', async () => {
// Create a Playwright Page and use mock-goto to remap the pages your script will visit
const browser = await chromium.launch();
const page = await browser.newPage();
const mock = mockGoto(page, {
paths: {
'https://somewebsite.com/': './html/main.html',
'https://somewebsite.com/f150.html': './html/f150.html',
'https://somewebsite.com/silverado.html': './html/silverado.html',
'https://somewebsite.com/ram.html': './html/ram.html',
},
});
// Call the script that you want to test.
const results = await myScript(page);
// Close the browser and restore the `goto` function
await browser.close();
mock.restore();
// Assert
// ...
});
});import puppeteer from 'puppeteer';
import mockGoto from 'mock-goto';
import myScript from './index';
describe('My script', () => {
it('Should return an array of trucks and for each, a list of engines', async () => {
// Create a Puppeteer Page and use mock-goto to remap the pages your script will visit
const browser = await puppeteer.launch();
const page = await browser.newPage();
const mock = mockGoto(page, {
paths: {
'https://somewebsite.com/': './html/main.html',
'https://somewebsite.com/f150.html': './html/f150.html',
'https://somewebsite.com/silverado.html': './html/silverado.html',
'https://somewebsite.com/ram.html': './html/ram.html',
},
});
// Call the script that you want to test.
const results = await myScript(page);
// Close the browser and restore the `goto` function
await browser.close();
mock.restore();
// Assert
// ...
});
});