React Test – How to write Unit test and e2e test (1)?

Unit test

Setup

  • Install ts-jest for testing TypeScript files
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
yarn add --dev jest typescript
yarn add --dev ts-jest @types/jest
yarn ts-jest config:init
yarn add --dev jest typescript yarn add --dev ts-jest @types/jest yarn ts-jest config:init
yarn add --dev jest typescript
yarn add --dev ts-jest @types/jest
yarn ts-jest config:init
  • Run yarn test or yarn jest

Test

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
/* 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')
})
/* 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') })
/* 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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"test": "jest --testPathIgnorePatterns=.*e2e.test.js",
"test": "jest --testPathIgnorePatterns=.*e2e.test.js",
"test": "jest --testPathIgnorePatterns=.*e2e.test.js",

e2e test

Use puppeteer and jest-puppeteer

Setup

  • Install packages
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
yarn add puppeteer jest-puppeteer --dev
yarn add @types/puppeteer @types/jest-environment-puppeteer @types/expect-puppeteer --dev
yarn add puppeteer jest-puppeteer --dev yarn add @types/puppeteer @types/jest-environment-puppeteer @types/expect-puppeteer --dev
yarn add puppeteer jest-puppeteer --dev
yarn add @types/puppeteer @types/jest-environment-puppeteer @types/expect-puppeteer --dev
  • Edit jest.config.js
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
/* 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',
},
}
/* 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', }, }
/* 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)
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
module.exports = {
launch: {
headless: process.env.HEADLESS !== 'false',
slowMo: process.env.SLOWMO ? process.env.SLOWMO : 0,
devtools: true,
},
}
module.exports = { launch: { headless: process.env.HEADLESS !== 'false', slowMo: process.env.SLOWMO ? process.env.SLOWMO : 0, devtools: true, }, }
module.exports = {
  launch: {
    headless: process.env.HEADLESS !== 'false',
    slowMo: process.env.SLOWMO ? process.env.SLOWMO : 0,
    devtools: true,
  },
}
  • Edit package.json
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"test:e2e": "jest --testPathPattern=.*e2e.test.js$",
"test:e2e": "jest --testPathPattern=.*e2e.test.js$",
"test:e2e": "jest --testPathPattern=.*e2e.test.js$",

Test

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// 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())
})
// 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()) })
// 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())
})


Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// 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
// 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
// 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
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// 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
// 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
// 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
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//div[@id="top-list"]/div[@data-list]
//div[@id="top-list"]/div[@data-list]
//div[@id="top-list"]/div[@data-list]

or

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//div[@id="top-list"]/div[@data-list="1"]
//div[@id="top-list"]/div[@data-list="1"]
//div[@id="top-list"]/div[@data-list="1"]

Be the first to comment

Leave a Reply

Your email address will not be published.


*