digital-resources icon indicating copy to clipboard operation
digital-resources copied to clipboard

Unit testing with `vitest`

Open ViorelMocanu opened this issue 1 year ago • 0 comments

Implement Vitest.

Docs here: https://docs.astro.build/en/guides/testing/

Example here: https://github.com/withastro/astro/tree/latest/examples/with-vitest

Steps for integration:

  • [ ] Dependency added in package.json, e.g. "vitest": "^0.34.2"
  • [ ] Create vitest.config.ts file as per these instructions and the following example:
import { getViteConfig } from 'astro/config';

export default getViteConfig({
  test: {
    // Vitest configuration options
  },
});
  • [ ] Create /test folder
  • [ ] Implement unit tests by writing files in the /test folder, such as basic.test.ts:
import { assert, expect, test } from 'vitest';

// Edit an assertion and save to see HMR in action

test('Math.sqrt()', () => {
	expect(Math.sqrt(4)).toBe(2);
	expect(Math.sqrt(144)).toBe(12);
	expect(Math.sqrt(2)).toBe(Math.SQRT2);
});

test('JSON', () => {
	const input = {
		foo: 'hello',
		bar: 'world',
	};

	const output = JSON.stringify(input);

	expect(output).eq('{"foo":"hello","bar":"world"}');
	assert.deepEqual(JSON.parse(output), input, 'matches original');
});

Example package.json setup:

    "test:unit": "cross-env NODE_ICU_DATA=node_modules/full-icu TZ=UTC vitest run",
    "test:unit:related": "cross-env NODE_ICU_DATA=node_modules/full-icu TZ=UTC vitest related",
    "test:unit:update": "pnpm test:unit --update",
    "test:unit:watch": "cross-env NODE_ICU_DATA=node_modules/full-icu TZ=UTC vitest watch",
    "test:unit:coverage": "pnpm test:unit --coverage",
    "test:e2e": "playwright test",

Add badge to readme.md like this: coverage

ViorelMocanu avatar Oct 04 '23 09:10 ViorelMocanu