Create Unit Test on Nuxt with vitest

Sample Code for Test - useCommonUtil.ts

export default () => {
  const isItemInListByType = <T>(
    list: T[] | undefined,
    key: keyof T,
    value: T
  ): boolean => {
    if (!list || list.length === 0) {
      console.error("List is empty or undefined.");
      return false;
    }

    const itemIndex = list.findIndex((item) => item[key] === value[key]);
    if (itemIndex === -1) {
      console.error(`Item with ${String(key)}=${value} not found in the list.`);
      return false;
    }

    return true;
  };

  return {
    isItemInListByType,
  };
};

Here is a step to add unit test in Nuxt Project

Setup For Test

  • Add Required Lib
bun add -d vitest @vitest/ui @vue/test-utils jsdom
  • Update your package.json to include a test script for running Vitest with Bun (Line 7)
"scripts": {
  "build": "nuxt build",
  "dev": "nuxt dev",
  "generate": "nuxt generate",
  "preview": "nuxt preview",
  "postinstall": "nuxt prepare",
  "test": "vitest"
}
  • Configure Vitest - Create a vitest.config.ts file in the root of your project
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: './vitest.setup.ts', // Optional: Add setup file for global configurations
  },
});

If you need to configure global settings (e.g., mocking or extending Jest matchers), create a vitest.setup.ts file

import '@testing-library/jest-dom';

Create a Test File

create a test on the same level as useCommonUtil.ts > useCommonUtil.test.ts

import useCommonUtil from './useCommonUtil';
import { describe, it, expect } from 'vitest'

describe('useCommonUtil', () => {
  const { isItemInListByType } = useCommonUtil();

  const sampleList = [
    { id: 1, name: 'Item 1' },
    { id: 2, name: 'Item 2' },
    { id: 3, name: 'Item 3' },
  ];

  it("should return true if the item exists in the list by key", () => {
    const result = isItemInListByType(sampleList, "id", { id: 2, name: "Item 2" });
    expect(result).toBe(true);
  });

  it("should return false if the item does not exist in the list by key", () => {
    const result = isItemInListByType(sampleList, "id", { id: 4, name: "Item 4" });
    expect(result).toBe(false);
  });

  it("should return false if the list is empty", () => {
    const result = isItemInListByType([], "id", { id: 1, name: "Item 1" });
    expect(result).toBe(false);
  });

  it("should return false if the list is undefined", () => {
    const result = isItemInListByType(undefined, "id", { id: 1, name: "Item 1" });
    expect(result).toBe(false);
  });

  it("should return false if the key does not match any item in the list", () => {
    const result = isItemInListByType(sampleList, "name", { id: 1, name: "Nonexistent Item" });
    expect(result).toBe(false);
  });

  it("should handle objects with additional properties gracefully", () => {
    const extendedList = [
      { id: 1, name: "Item 1", extra: "Extra 1" },
      { id: 2, name: "Item 2", extra: "Extra 2" },
    ];
    const result = isItemInListByType(extendedList, "id", { id: 1, name: "Item 1", extra: "Extra 1" });
    expect(result).toBe(true);
  });
});

Run Tests

bun test

Sample Run Result

bun test v1.2.2 (c1708ea6)

composables\useCommonUtil.test.ts:
✓ useCommonUtil > should return true if the item exists in the list by key
Item with id=[object Object] not found in the list.
✓ useCommonUtil > should return false if the item does not exist in the list by key
List is empty or undefined.
✓ useCommonUtil > should return false if the list is empty
List is empty or undefined.
✓ useCommonUtil > should return false if the list is undefined
Item with name=[object Object] not found in the list.
✓ useCommonUtil > should return false if the key does not match any item in the list
✓ useCommonUtil > should handle objects with additional properties gracefully

 6 pass
 0 fail
 6 expect() calls
Ran 6 tests across 1 files.

Reference


Discover more from naiwaen@DebuggingSoft

Subscribe to get the latest posts sent to your email.