JavaScript testing using Vitest

By John Keyes

June 25, 2024 at 12:52

javascript javascript testing vitest

What is Vitest?

Vitest aims to position itself as the Test Runner of choice for Vite projects, and as a solid alternative even for projects not using Vite.

Installation

npm install -D vitest

Naming test files

Permitted by default:

If your file is test_utils.js this will no be found by the test collector:

$ npx vitest --run tests/test_xml.js 

 RUN  v1.5.3 /datadisk/tapadoo/freeagent/js/freeagent

filter:  tests/test_xml.js
include: **/*.{test,spec}.?(c|m)[jt]s?(x)
exclude:  **/node_modules/**, **/dist/**, **/cypress/**, **/.{idea,git,cache,output,temp}/**, **/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build,eslint,prettier}.config.*
watch exclude:  **/node_modules/**, **/dist/**

No test files found, exiting with code 1

Writing tests

/* tests/utils.test.js */
import { expect, test } from 'vitest';
import { toUpper } from '../src/utils';

test('toUpper letters', () => {
  expect("ABC").toBe(toUpper("abc"));
  expect("ABC").toBe(toUpper("aBc"));
  expect("VITE").toBe(toUpper("Vite"));
});

Running

All tests in a directory

$ npx vitest --run tests

 RUN  v1.5.3 /datadisk/tapadoo/freeagent/js/freeagent

Using vars defined in .dev.vars
[vpw:inf] Starting isolated runtimes for vitest.config.js...
 ✓ tests/utils.test.js (1)
   ✓ toUpper letters

 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  14:17:17
   Duration  1.56s (transform 23ms, setup 0ms, collect 22ms, tests 17ms, environment 1ms, prepare 324ms)

[vpw:dbg] Shutting down runtimes...

A specific test file

npx vitest --run tests/utils.test.js

Failing tests

Adding the following expect:

    expect("").toBe(toUpper("xyz"));

is recorded as a failure in the output:

 ❯ tests/utils.test.js (1)
   × toUpper letters

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯

 FAIL  tests/utils.test.js > toUpper letters
AssertionError: expected '123' to be 'XYZ' // Object.is equality

- Expected
+ Received

- XYZ
+ 123

 ❯ tests/utils.test.js:9:17
      7|   expect("ABC").toBe(toUpper("aBc"));
      8|   expect("VITE").toBe(toUpper("Vite"));
      9|   expect("123").toBe(toUpper("xyz"));
       |                 ^
     10| });

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]
 Test Files  1 failed (1)
      Tests  1 failed (1)
   Start at  14:27:02
   Duration  1.63s (transform 24ms, setup 0ms, collect 25ms, tests 21ms, environment 1ms, prepare 323ms

References

Last updated: June 25, 2024 at 12:52