Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add testRuleConfigs function #68

Merged
merged 6 commits into from
Aug 10, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Head

- Added: `testInvalidRuleConfigs` function.

## 6.1.1

- Fixed: tightly-coupled dependency on Stylelint's internal module `lib/utils/getOsEol`.
Expand Down
40 changes: 34 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

[![NPM version](https://img.shields.io/npm/v/jest-preset-stylelint.svg)](https://www.npmjs.org/package/jest-preset-stylelint) [![Build Status](https://github.com/stylelint/jest-preset-stylelint/workflows/CI/badge.svg)](https://github.com/stylelint/jest-preset-stylelint/actions)

[Jest](https://facebook.github.io/jest/) preset for [Stylelint](https://github.com/stylelint) plugins.
[Jest](https://jestjs.io/) preset for [Stylelint](https://stylelint.io/) plugins.

## Installation

Expand All @@ -22,14 +22,17 @@ Add the preset to your `jest.config.js` or `jest` field in `package.json`:
}
```

Optionally, you can avoid specifying `plugins` in every schema by defining your own setup file to configure the `testRule` function. This is useful if you have many tests. There are two additional steps to do this:
Optionally, you can avoid specifying `plugins` in every schema by defining your own setup file to configure the `testRule`/`testInvalidRuleConfigs` functions.
This is useful if you have many tests. There are two additional steps to do this:

1. Create `jest.setup.js` in the root of your project. Provide `plugins` option to `getTestRule()`:
1. Create `jest.setup.js` in the root of your project. Provide `plugins` option to `getTestRule`/`getTestInvalidRuleConfigs`:

<!-- prettier-ignore -->
```js
const { getTestRule } = require("jest-preset-stylelint");

global.testRule = getTestRule({ plugins: ["./"] });
global.testInvalidRuleConfigs = getTestInvalidRuleConfigs({ plugins: ["./"] });
```

2. Add `jest.setup.js` to your `jest.config.js` or `jest` field in `package.json`:
Expand All @@ -43,7 +46,13 @@ Optionally, you can avoid specifying `plugins` in every schema by defining your

## Usage

The preset exposes a global `testRule` function that you can use to efficiently test your plugin using a schema.
This preset exposes the following global functions as a helper.

See also the [type definitions](index.d.ts) for more details.

### `testRule`

The `testRule` function enables you to efficiently test your plugin using a schema.

For example, we can test a plugin that enforces and autofixes kebab-case class selectors:

Expand Down Expand Up @@ -104,9 +113,28 @@ testRule({
});
```

## Schema properties
### `testInvalidRuleConfigs`

The `testInvalidRuleConfigs` function enables you to test invalid configs for a rule.

For example:

```js
testInvalidRuleConfigs({
plugins: ["."],
ruleName,

See the [type definitions](index.d.ts).
configs: [
ybiquitous marked this conversation as resolved.
Show resolved Hide resolved
{
config: "invalid"
},
{
config: [/invalid/],
description: "regex is not allowed"
}
]
});
```

## [Changelog](CHANGELOG.md)

Expand Down
44 changes: 44 additions & 0 deletions __tests__/fixtures/plugin-foo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
'use strict';

const stylelint = require('stylelint');

const ruleName = 'plugin/foo';

const messages = stylelint.utils.ruleMessages(ruleName, {
rejected: (selector) => `No "${selector}" selector`,
});

/** @type {(value: unknown) => boolean} */
const isString = (value) => typeof value === 'string';

/** @type {import('stylelint').Rule} */
const ruleFunction = (primary) => {
return (root, result) => {
const validOptions = stylelint.utils.validateOptions(result, ruleName, {
actual: primary,
possible: [isString],
});

if (!validOptions) {
return;
}

root.walkRules((rule) => {
const { selector } = rule;

if (primary !== selector) {
stylelint.utils.report({
result,
ruleName,
message: messages.rejected(selector),
node: rule,
});
}
});
};
};

ruleFunction.ruleName = ruleName;
ruleFunction.messages = messages;

module.exports = stylelint.createPlugin(ruleName, ruleFunction);
20 changes: 20 additions & 0 deletions __tests__/getTestInvalidRuleConfigs.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
'use strict';

const getTestInvalidRuleConfigs = require('../getTestInvalidRuleConfigs.js');

const testInvalidRuleConfigs = getTestInvalidRuleConfigs();

testInvalidRuleConfigs({
plugins: [require.resolve('./fixtures/plugin-foo.js')],
ruleName: 'plugin/foo',

configs: [
{
config: 123,
},
{
config: [/foo/],
description: 'regex is not allowed',
},
],
});
33 changes: 33 additions & 0 deletions __tests__/getTestRule.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'use strict';

const getTestRule = require('../getTestRule.js');

const testRule = getTestRule();

testRule({
plugins: [require.resolve('./fixtures/plugin-foo.js')],
ruleName: 'plugin/foo',
config: ['.a'],

accept: [
{
code: '.a {}',
},
{
code: '.a {}',
description: 'with description',
},
],

reject: [
{
code: '#a {}',
message: 'No "#a" selector (plugin/foo)',
},
{
code: '#a {}',
message: 'No "#a" selector (plugin/foo)',
description: 'with description',
},
],
});
49 changes: 49 additions & 0 deletions getTestInvalidRuleConfigs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
'use strict';

const { inspect } = require('util');

/** @type {import('.').getTestInvalidRuleConfigs} */
module.exports = function getTestInvalidRuleConfigs(options = {}) {
return function testInvalidRuleConfigs({
ruleName,
configs,
only,
skip,
plugins = options.plugins,
}) {
if (configs.length === 0) {
throw new TypeError('The "configs" property must not be empty');
}

/** @type {import('stylelint').lint} */
let lint;

beforeAll(() => {
// eslint-disable-next-line n/no-unpublished-require
lint = require('stylelint').lint;
});

const testGroup = only ? describe.only : skip ? describe.skip : describe;

testGroup(`${ruleName} invalid configs`, () => {
for (const { config, description, only: onlyTest, skip: skipTest } of configs) {
const testFn = onlyTest ? test.only : skipTest ? test.skip : test;

/* eslint-disable jest/no-standalone-expect */
testFn(`${description || inspect(config)}`, async () => {
const lintConfig = {
plugins,
rules: { [ruleName]: config },
};
const output = await lint({ code: '', config: lintConfig });

expect(output.results).toHaveLength(1);
expect(output.results[0].invalidOptionWarnings).toEqual([
{ text: expect.stringMatching(`"${ruleName}"`) },
]);
});
/* eslint-enable jest/no-standalone-expect */
}
});
};
};
22 changes: 22 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,28 @@ export type TestRule = (schema: TestSchema) => void;
*/
export function getTestRule(options?: { plugins?: TestSchema['plugins'] }): TestRule;

/**
* Test invalid configurations for a rule.
*/
export type TestInvalidRuleConfigs = (
schema: Pick<TestSchema, 'ruleName' | 'plugins' | 'only' | 'skip'> & {
configs: {
config: unknown;
description?: string;
only?: boolean;
skip?: boolean;
}[];
},
) => void;

/**
* Create a `testInvalidRuleConfigs()` function with any specified plugins.
*/
export function getTestInvalidRuleConfigs(options?: {
plugins?: TestSchema['plugins'];
}): TestInvalidRuleConfigs;

declare global {
var testRule: TestRule;
var testInvalidRuleConfigs: TestInvalidRuleConfigs;
}
4 changes: 3 additions & 1 deletion jest-setup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

const getTestRule = require('./getTestRule');
const getTestRule = require('./getTestRule.js');
const getTestInvalidRuleConfigs = require('./getTestInvalidRuleConfigs.js');

global.testRule = getTestRule();
global.testInvalidRuleConfigs = getTestInvalidRuleConfigs();
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"main": "index.js",
"types": "index.d.ts",
"files": [
"getTestInvalidRuleConfigs.js",
"getTestRule.js",
"jest-preset.js",
"jest-setup.js",
Expand Down Expand Up @@ -55,6 +56,10 @@
"@stylelint/remark-preset"
]
},
"jest": {
"preset": "./jest-preset.js",
"testRegex": ".*\\.test\\.js$"
},
"devDependencies": {
"@stylelint/prettier-config": "^3.0.0",
"@stylelint/remark-preset": "^4.0.0",
Expand Down