Execute snapshot testing by using Jest and puppeteer
We can test your application/website by using Jest and puppeteer. And sometimes, we want to detect what HTML h […]
広告ここから
広告ここまで
目次
We can test your application/website by using Jest and puppeteer. And sometimes, we want to detect what HTML has been changed.
In this post, I’ll note how to execute snapshot testing in the Jest with Puppeteer.
Example code of the test
We can get rendered HTML by using $().getProperty('outerHTML')
.
So we can easy to create snapshot by using the function.
const shouldMatchOuterHTMLSnapshot = async (selector) => {
// Find element
const elementHandle = await page.$(selector);
// Get outer HTML
const jsHandle = await elementHandle.getProperty('outerHTML');
// To JSON
const json = await jsHandle.jsonValue();
// Test it
expect(json).toMatchSnapshot()
}
describe('test', () => {
beforeAll(async () => {
await page.goto('http://localhost:3000');
});
afterAll(async done => {
done();
});
it('should match snapshot [body]', async () => {
await shouldMatchOuterHTMLSnapshot('#root')
});
it('should match snapshot [Login form]', async () => {
await shouldMatchOuterHTMLSnapshot('[data-test="login.form"]')
});
})
After execute Jest test, we can get the following snapshot
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`test should match snapshot [body] 1`] = `"<div id=\\"root\\"><div class=\\"amplify-container\\">
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`should match snapshot [Login form] 1`] = `"<form data-test=\\"login.form\\" class=\\"ui fo
Detect HTML change
After creating a snapshot, we can easy to detect the page’s HTML changes.