5.1.0 • Published 4 days ago

@leaflink/dom-testing-utils v5.1.0

Weekly downloads
-
License
MIT
Repository
-
Last release
4 days ago

@leaflink/dom-testing-utils

Leaflink repository to manage test utilities to be shared across front-end applications.

version downloads MIT License semantic-release Commitizen friendly

Installation

npm install --save-dev @leaflink/dom-testing-utils

Usage

In your *.spec.(ts|js) files you can import utility functions.

import {
  waitForLoadingToFinish,
  cleanupDropdowns,
  assertAndDismissNoty,
  cleanupNoty,
  createFixtureGenerator,
} from '@leaflink/dom-testing-utils';

it('...', () => {
  cleanupNoty();
});

There's also shared setup files you can extend from.

Global setup

Add the following line to your vite.config.js:

globalSetup: 'node_modules/@leaflink/dom-testing-utils/dist/global-setup.js',

This will run once before everything. See https://vitest.dev/config/#globalsetup.

Setup file

Add the following line to your vite.config.js:

setupFiles: ['node_modules/@leaflink/dom-testing-utils/dist/setup-env.js'],

This will be run once before each test file. See https://vitest.dev/config/#setupfiles.

cleanupNoty

Helper method to remove all noty alerts from the DOM.

Parameters: None

Returns: void

waitForLoadingToFinish

Utility to wait for loading to complete. Need to add a data-test to any loading elements. Defaults to ll-loading or loading-spinner if testId is not specified.

ParametersTypeDefaultSummary
testIdstringll-loading && loading-spinnerThe data test ID to target.

Returns: Promise<boolean>

Will resolve or throw if the loaders stay in the DOM.

cleanupDropdowns

Helper method to remove all floating Stash Dropdown elements from the DOM.

Parameters: None

Returns: void

assertAndDismissNoty

Helper to assert and manually dismiss a notification. This is useful in scenarios where cleanupNoty() does not work as expected, such as when validating error messages in test suites.

ParametersTypeDefaultSummary
textstringRequiredExpected notification text.

Returns: void

createFixtureGenerator

Higher order function that takes a method whose responsibility is to create a single data fixture object and returns a new generator function that allows you to create 1 or more of those fixtures. Fixture generator function that's returned supports passing optional num and overrides params.

ParametersTypeDefaultSummary
fixtureFnfunctionRequiredMethod that generates and returns a single data object.

Returns

(num?, overrides?) => Array<{[key: string]: any}> | {[key: string]: any}
// OR
(overrides?) => {[key: string]: any}

A new generator function that accepts a number & overrides where:

  • num = The number of fake data objects to generate. Defaults to 1
  • overrides = Specific attributes you want to override in each data fixture object.

When calling the returned function, you'll get an array OR object of fixture data (It will be a single object if num = 1).

Examples

Quick example:

const generateInvoice = (overrides) => ({ id: uuid(), balance: 15799, classification: "Adult Use", ...overrides});
const generateInvoices = createFixtureGenerator(generateInvoice);

generateInvoices()
// => Single invoice object

generateInvoices(1)
// => Single invoice object

generateInvoices(1, { foo: 'bar' })
// => Single invoice object, override `foo` to equal `'bar'`

generateInvoices({ foo: 'bar' })
// => Single invoice object, override `foo` to equal `'bar'`

generateInvoices(10)
// => Array of 10 invoice objects

generateInvoices(10, { foo: 'bar' })
// => Array of 10 invoice objects, override `foo` to equal `'bar'` in each

Full example:

// tests/fixtures/products.ts
import { faker } from '@faker-js/faker';
import { createFixtureGenerator } from '@leaflink/dom-testing-utils';

export const generateProduct = (overrides = {}) => ({
  sku: git.commitSha(),
  name: faker.commerce.productName(),
  quantity: faker.random.number(100),
  cases: faker.random.number(10),
  ...overrides,
});

export default createFixtureGenerator(generateProduct);

// services/api/products.ts
import generateProducts from '@/tests/fixtures/products';

// ...
const mockProducts = generateProducts(10, { cases: 25 })
// ...

Mocking API Endpoints

In order to mock API endpoints that your tests interact with, you can get a set of mocking functions from createMockApiUtils.

import { createMockApiUtils } from '@leaflink/dom-testing-utils';
import yourServer from './server.ts';

const {
  mockGetData,
  mockGetEndpoint,
  mockPatchData,
  // etc.
} = createMockApiUtils(yourServer);

There are two flavors of mocking utility functions: 1. mock{VERB}Data - mocks response with a singular data object 2. mock{VERB}Endpoint - mocks a response endpoint with a function like msw's Response Resolver

To mock an endpoint with simple return data

  mockGetData('/relative-url', myMockObj);

or you can customize the response

  mockGetEndpoint('/relative-url', (req, res, ctx) => {
    if (someConditional()) {
      res(ctx.json(true));
    } else {
      res(ctx.json(false));
    }
  });
5.1.0

10 days ago

5.0.0

11 days ago

4.2.3

3 months ago

4.2.2

3 months ago

4.2.1

3 months ago

4.2.0

5 months ago

4.0.1

5 months ago

4.1.0

5 months ago

1.3.0

10 months ago

2.3.0

6 months ago

2.1.2

7 months ago

2.2.0

7 months ago

2.1.1

8 months ago

2.1.0

8 months ago

2.0.0

8 months ago

3.0.1

6 months ago

3.0.0

6 months ago

4.0.0

5 months ago

1.2.0

11 months ago

1.2.1

11 months ago

1.1.1

1 year ago

1.1.0

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago