Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Last active January 6, 2024 22:33
Show Gist options
  • Select an option

  • Save wilmoore/3d1be59993f833d8f99aed0e029fee06 to your computer and use it in GitHub Desktop.

Select an option

Save wilmoore/3d1be59993f833d8f99aed0e029fee06 to your computer and use it in GitHub Desktop.
JavaScript :: Testing :: Jest :: Courses :: JavaScript Unit Testing with Jest :: 2. Writing Your First Unit Test with Jest

⪼ Made with 💜 by Polyglot.

Version Check

  • JavaScript 2022
  • Jest v29
  • Node.js v18
  • npm v8

Why Write Unit Tests?

  • Manual testing takes too much time
  • Unit tests can be run automatically
  • Give us confidence in the quality of our source code
  • Can facilitate Test-Driven Development (TDD)
  • Can act like documentation

Test Pyramid

  • E2E Tests
  • Integeration Tests
  • Unit Tests

image

Overview

  • Why are unit tests so important?
  • Jest installation
  • Writing basic unit tests with Jest
  • Using common matchers
  • Using mocks
  • Testing asyncronous functions
  • Measuring code coverage

Key Benefits of Using Jest

  • No configuration required to get started
  • Highly intuitive API
  • Runs test in parallel
  • Works with the vast majority of JS projects
  • Great documentation and a large community

Install Jest

» npm install jest --save-dev

test Pacakage Script

add "jest" to the test script

» npm test

test

Parameters

  • name: Test's Name
  • fn: Test Function
  • timeout: The timeout for an async function test

expect(actual)

The argument for the expect function is the value that you want to validate (actual)


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment