Unittest Jest - rimander123/react-js-training-course GitHub Wiki

Get started

Initial documentation about Jest

Install or have binary package of Node JS LTS 64Bits

Install Node JS

Also add the binary files in your PATH environment variable

Install YARN package manager

Using NPM command line

npm install -g yarn@berry

Create a JEST unit test from zero

Creare a new React project , if you have one, please skip this step

Initialize react project by running this command

npm init

Install Typescript and Jest tools

Over your react project files, you need to add TypeScript, Jest and ts-jest

npm install --save-dev jest @types/jest @types/node ts-jest typescript

Create Jest's config file in root project's path

jest.config.js

module.exports = {
  roots: ['<rootDir>/src'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  }
}

For configuration here full documentation for Jest's config

Create Typescript config

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": ["es2015"],
    "strict": true,
    "declaration": true,
    "outDir": "dist",
    "sourceMap": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}

For more information checkout those links

TypeScript config

TsConfig

Create main script file

src/main.ts

// in this function sample only pass a string and check if is an internal link
export const isInternalLink = (link: string) => /^\/(?!\/)/.test(link)

Create testing script file

src/main.spec.ts

import { isInternalLink } from './main'

test('should return false given external link', () => {
  expect(isInternalLink('https://google.com')).toBe(false)
})

test('should return true given internal link', () => {
  expect(isInternalLink('/some-page')).toBe(true)
})

Create script command line

Edit your package.json and add or replace this lines

"scripts": {
    "test": "jest"
  },

Execute unit test

In your command line run this command

npm test

Results

If all is OK, you must to see the next result

> jest

 PASS  src/main.spec.ts
  √ should return false given external link (3ms)
  √ should return true given internal link

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        10.386s
Ran all test suites.
⚠️ **GitHub.com Fallback** ⚠️