Setup using jest
jest
is the traditional and most popular testing solution.
TIP
You can see the described example as a code in the repository here.
Author's Note
If you are starting a new project - first consider using vite
as a test-runner.
In most scenarios it is faster, easier to configure and has better documentation.
Note
This section shows the minimal configuration - for full features and nice defaults, check out the API Reference
section or inspect all the options inline using editor's suggestions.
First, install jest
itself and some additional packages that you will need to get started:
npm add -D jest-expect-message
yarn add -D jest-expect-message
pnpm add -D jest-expect-message
If you are using TypeScript, install the modules required by jest
to work with it:
npm add -D ts-jest ts-node @types/jest
yarn add -D ts-jest ts-node @types/jest
pnpm add -D ts-jest ts-node @types/jest
Next, create a jest
config file with the following content (at least):
import type { JestConfigWithTsJest } from 'ts-jest';
export default {
testEnvironment: 'node',
transform: {
'^.+.tsx?$': ['ts-jest', {}],
},
} as JestConfigWithTsJest;
Next, create a file that will export functions for testing:
// 1. Import the factory that will create functions bound to `jest`
import { createTestUtils } from '@morev/stylelint-testing-library';
// 2. Import a module that extends `jest` matchers
// for more detailed error messages
import 'jest-expect-message';
// 3. Create testing functions
// To see all available `createTestUtils` options, please
// refer to the `API Reference` section of this documentation
// or use inline IDE suggestions.
const { createTestRule, createTestRuleConfig } = createTestUtils();
// 4. Export these functions
// Unfortunately, you will need to import these functions
// within each of your test files, as `jest` test functions
// (`describe`, `it`, `expect`, etc) only exist in the context of such files.
// If you know how to access these variables outside this context -
// feel free to create a PR or issue.
export { createTestRule, createTestRuleConfig };
import { createTestUtils } from '@morev/stylelint-testing-library';
import 'jest-expect-message';
const { createTestRule, createTestRuleConfig } = createTestUtils();
export { createTestRule, createTestRuleConfig };
Next, create a script for testing in your package.json
:
{
"name": "your-awesome-stylelint-plugin",
"scripts": {
"test": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js"
},
}
and you are ready to test your rules using the npm run test
command:
import { createTestRule, createTestRuleConfig } from '../testing-functions';
import { messages, ruleName } from './lowercase-selectors';
const testRule = createTestRule({ ruleName });
const testRuleConfig = createTestRuleConfig({ ruleName });
testRuleConfig({ /* ... */ });
testRule({ /* ... */ });
We're all set!
Next, follow the instructions on the Usage
page.