JavaScriptJestNode.jsPuppeteer

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.

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts