Skip to content

Instantly share code, notes, and snippets.

@t-lock
Last active April 24, 2020 08:03
Show Gist options
  • Save t-lock/f6729fbc90f1621615de0aa12a484be9 to your computer and use it in GitHub Desktop.
Save t-lock/f6729fbc90f1621615de0aa12a484be9 to your computer and use it in GitHub Desktop.
helper for mocking responses in puppeteer
export async function useMocks(page, mocks) {
await page.setRequestInterception(true);
page.on("request", async (request) => {
if (request.postData() && JSON.parse(request.postData()).operationName) {
const mock = mocks.find(
(mock) => mock.name === JSON.parse(request.postData()).operationName
);
if (mock) {
await delay(500);
request.respond({
content: "application/json",
headers: { "Access-Control-Allow-Origin": "*" },
body: JSON.stringify(mock.response),
});
return;
}
}
request.continue();
return;
});
}
// usage
import puppeteer from "puppeteer"
import { useMocks } from "./useMocks";
let browser = await puppeteer.launch({ headless: false });
let page = await browser.newPage();
useMocks(page, [
{
name: "GetCurrentUser",
response: {
data: {
currentUser: {
id: 1,
name: "My user",
__typename: "User"
}
}
}
},
{
name: "UpdateUser",
response: {
data: {
user: {
id: 1,
name: "My mutated user",
__typename: "User"
}
}
}
}
]);
// continue testing as normal,
// ...with mocked CurrentUser query and UpdateUser mutations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment