Unit test
Setup
- Install ts-jest for testing TypeScript files
yarn add --dev jest typescript yarn add --dev ts-jest @types/jest yarn ts-jest config:init
- Run
yarn test
oryarn jest
Test
/* eslint-disable no-undef */ const { getMeetCode } = require('src/pages/Home/format') test('retrieve a teacher', () => { const mock = [ { id: '5168779', isStudent: true, isTeacher: false, }, { id: '5198724', isStudent: false, isTeacher: true, }, ] expect(getMeetCode(mock)).toBe('5198724') })
Problems
How to ignore a specific file type “e2e.test.js”?
Edit package.json file
"test": "jest --testPathIgnorePatterns=.*e2e.test.js",
e2e test
Use puppeteer and jest-puppeteer
Setup
- Install packages
yarn add puppeteer jest-puppeteer --dev yarn add @types/puppeteer @types/jest-environment-puppeteer @types/expect-puppeteer --dev
- Edit jest.config.js
/* eslint-disable no-undef */ /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ const ts_preset = require('ts-jest/jest-preset') const puppeteer_preset = require('jest-puppeteer/jest-preset') module.exports = { ...ts_preset, ...puppeteer_preset, globals: { URL: 'http://localhost:3004', }, }
- Create jest-puppeteer.config.js (Optional)
module.exports = { launch: { headless: process.env.HEADLESS !== 'false', slowMo: process.env.SLOWMO ? process.env.SLOWMO : 0, devtools: true, }, }
- Edit package.json
"test:e2e": "jest --testPathPattern=.*e2e.test.js$",
Test
// testPage.e2e.test.js /* eslint-disable no-undef */ const puppeteer = require('puppeteer') ... const mockURL = 'http://localhost:3004/xxxx' describe('Check something...', () => { let browser let page beforeAll(async () => { browser = await puppeteer.launch({ headless: false, }) page = await browser.newPage() await page.setViewport({ width: 1366, height: 768 }) await page.goto(mockURL) }, 30000) // timeout 30s /////////////// // Body it('Should display data table', async () => { await testDataTable(page) }) // End afterAll(() => browser.close()) })
// testDataTable.js /* eslint-disable no-undef */ const { isVisible } = require('./utils/utils') const testDataTable = async (page) => { const isDisplayed = await isVisible( page, '//div[@id="id-data-table"]' ) if (!isDisplayed) { await takeScreenshot(page, 'ErrorDataTable') throw 'Data table not found' } } exports.testDataTable = testDataTable
// utils.js const takeScreenshot = async (page, fileName) => { await page.screenshot({ path: `./__test___/end2end/screenshots/${fileName}.png`, fullPage: true, // take a full page screenshot }) } const isVisible = async (page, xPathSelector) => { try { await page.waitForXPath(xPathSelector, { visible: true, timeout: 2000 }) return true } catch { return false } } exports.isVisible = isVisible exports.takeScreenshot = takeScreenshot
For more in detail with puppeteer, please refer
XPath
- Locate node with specific attribute
//div[@id="top-list"]/div[@data-list]
or
//div[@id="top-list"]/div[@data-list="1"]
Leave a Reply