Online Lectures/JavaScript Unit Testing - The Practical

Section6: Advanced Testing Concepts

Nomad Kim 2023. 4. 5. 06:37

More Key Testing Library APIs

  • toBe() vs toEqual()
  • Testing Asynchronous Code
  • Using Setup & Cleanup Hooks

 

toBe vs toEqual()

Use "toEqual" method for deep-comparison on values not address of the object. In contrary, toBe method does shallow comparison.

 

Testing Asynchronous Code

test code here

 

case1. callback

use DoneCallback

  • Vitest and Jest will pick up errors and consider the test to have failed and show the reason why it failed.
    • But if using done, errors won't be picked up by test runner.
    • This shows Error: Test timed out in 5000ms.
    • Thus, necessary to use try-catch.
  • Test will not wait for any inner callback functions to finish.
    • Should add “done” after the end of testing code completed.
    • Then, test(Vitest and Jest) will wait until done is called.
    • And then, it will run expect codes.

case2. promise

1. resolves method

expect(Promise result).resolves.(wanted method)

 

2. async-await syntax

it("should generate a token value", async () => {
  const testUserEmail = "test@test.com";

  const token = await generateTokenPromise(testUserEmail);

  expect(token).toBeDefined();
})

 

Setup & Cleanup Hooks

test codes here

 

1. beforeAll, beforeEach, afterEach, afterAll

  • when using identical variables for testing and needing reset the variables, hooks are required to use as above
  • If there are suites using global variable, beforeAll or afterAll is useful.
  • or if there are each single tests using global variables, beforeEach or afterEach is required.

2. concurrent

  • there are 2 ways of executing tests in parallel for speed-up
1. describe.concurrent(()=>{
  include tests!
  })
2. it.concurrent on each tests