Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[pigment] Improve testing of fixtures (mui#41389)
Browse files Browse the repository at this point in the history
Co-authored-by: siriwatknp <siriwatkunaporn@gmail.com>
2 people authored and mnajdova committed Mar 8, 2024

Verified

This commit was signed with the committer’s verified signature.
hediet Henning Dieterichs
1 parent 39a0a61 commit 230b282
Showing 21 changed files with 306 additions and 115 deletions.
2 changes: 1 addition & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
@@ -23,7 +23,7 @@
/packages/pigment-react/processors/
/packages/pigment-react/exports/
/packages/pigment-react/theme/
/packages/pigment-react/tests/fixtures/
/packages/pigment-react/tests/**/fixtures
/packages/pigment-nextjs-plugin/loader.js
# Ignore fixtures
/packages-internal/scripts/typescript-to-proptypes/test/*/*
3 changes: 3 additions & 0 deletions packages/pigment-react/package.json
Original file line number Diff line number Diff line change
@@ -26,6 +26,7 @@
"copy-license": "node ../../scripts/pigment-license.mjs",
"build": "tsup",
"test": "cd ../../ && cross-env NODE_ENV=test mocha 'packages/pigment-react/**/*.test.{js,ts,tsx}'",
"test:update": "cd ../../ && cross-env NODE_ENV=test UPDATE_FIXTURES=true mocha 'packages/pigment-react/**/*.test.{js,ts,tsx}'",
"test:ci": "cd ../../ && cross-env NODE_ENV=test BABEL_ENV=coverage nyc --reporter=lcov --report-dir=./coverage/pigment-react mocha 'packages/pigment-react/**/*.test.{js,ts,tsx}'",
"typecheck": "tsc --noEmit -p ."
},
@@ -53,12 +54,14 @@
"@types/babel__core": "^7.20.5",
"@types/babel__helper-module-imports": "^7.18.3",
"@types/babel__helper-plugin-utils": "^7.10.3",
"@types/chai": "^4.3.12",
"@types/cssesc": "^3.0.2",
"@types/lodash": "^4.14.202",
"@types/node": "^18.19.21",
"@types/react": "^18.2.55",
"@types/stylis": "^4.2.5",
"chai": "^4.4.1",
"prettier": "^3.2.5",
"react": "^18.2.0"
},
"peerDependencies": {
36 changes: 34 additions & 2 deletions packages/pigment-react/tests/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,35 @@
# Adding new fixtures
# Pigment CSS testing

Create a new file name with `[name].input.js` and add `styled`, `css` or other zero-runtime calls into the file. Also add equivalent `[name].output.js` and `[name].output.css` and run the test. After the new test fails, get the results from the received output and add it to the equivalent js and css files. This is equivalent to snapshot testing and will make sure any change in internal css generation logic does not fail any other existing tests.
## Folder structure

- `tests` is the root folder for all tests
- `fixtures` contains all the fixtures for the tests
- `*.input.js` are the input files created manually
- `*.output.*` are the expected output files created by running the tests
- `*.test.js` are the test files that run the fixtures

## Running tests

At the root project terminal:

```bash
pnpm nx run @pigment-css/react:test
```

To update the output fixtures:

```bash
pnpm nx run @pigment-css/react:test:update
```

## Adding new tests

Each folder inside `tests` is a Pigment CSS feature. To add a new test, create a new folder with the feature name and add a new test file with the `.test.js` extension. Inside the test file, import the fixtures and run the tests.

## Adding new fixtures

Create a new file name with `[name].input.js` and add `styled`, `css` or other Pigment CSS calls into the file.

The first time you run the tests, the output files will be created automatically. Then check the output files to make sure they are correct.

For any implementation changes after that, if you want to update the output files, run the tests with the `test:update` script.
40 changes: 40 additions & 0 deletions packages/pigment-react/tests/css/css.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import path from 'node:path';
import { runTransformation, expect } from '../testUtils';

const theme = {
palette: {
primary: {
main: 'red',
},
},
size: {
font: {
h1: '3rem',
},
},
components: {
MuiSlider: {
styleOverrides: {
rail: {
fontSize: '3rem',
},
},
},
},
};

describe('Pigment CSS - css', () => {
it('basics', async () => {
const { output, fixture } = await runTransformation(
path.join(__dirname, 'fixtures/css.input.js'),
{
themeArgs: {
theme,
},
},
);

expect(output.js).to.equal(fixture.js);
expect(output.css).to.equal(fixture.css);
});
});
6 changes: 6 additions & 0 deletions packages/pigment-react/tests/css/fixtures/css.input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { css } from '@pigment-css/react';

const cls1 = css`
color: ${({ theme }) => theme.palette.primary.main};
font-size: ${({ theme }) => theme.size.font.h1};
`;
4 changes: 4 additions & 0 deletions packages/pigment-react/tests/css/fixtures/css.output.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.c1wr0t7p {
color: red;
font-size: 3rem;
}
1 change: 1 addition & 0 deletions packages/pigment-react/tests/css/fixtures/css.output.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
const cls1 = 'c1wr0t7p';
6 changes: 0 additions & 6 deletions packages/pigment-react/tests/fixtures/styled.output.css

This file was deleted.

17 changes: 0 additions & 17 deletions packages/pigment-react/tests/fixtures/styled.output.js

This file was deleted.

10 changes: 10 additions & 0 deletions packages/pigment-react/tests/keyframes/fixtures/keyframes.input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { keyframes } from '@pigment-css/react';

const rotateKeyframe = keyframes({
from: {
transform: 'rotate(360deg)',
},
to: {
transform: 'rotate(0deg)',
},
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
@keyframes r14c1bqo {
from {
transform: rotate(360deg);
}
to {
transform: rotate(0deg);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
const rotateKeyframe = 'r14c1bqo';
13 changes: 13 additions & 0 deletions packages/pigment-react/tests/keyframes/keyframes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import path from 'node:path';
import { runTransformation, expect } from '../testUtils';

describe('Pigment CSS - keyframes', () => {
it('basics', async () => {
const { output, fixture } = await runTransformation(
path.join(__dirname, 'fixtures/keyframes.input.js'),
);

expect(output.js).to.equal(fixture.js);
expect(output.css).to.equal(fixture.css);
});
});
81 changes: 0 additions & 81 deletions packages/pigment-react/tests/pigment.test.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { styled, keyframes, css } from '@pigment-css/react';
import { styled, keyframes } from '@pigment-css/react';

const rotateKeyframe = keyframes({
from: {
@@ -14,16 +14,11 @@ const Component = styled.div(({ theme }) => ({
animation: `${rotateKeyframe} 2s ease-out 0s infinite`,
}));

const cls1 = css`
color: ${({ theme }) => theme.palette.primary.main};
font-size: ${({ theme }) => theme.size.font.h1};
`;

const SliderRail = styled('span', {
name: 'MuiSlider',
slot: 'Rail',
})`
display: block;
display: none;
position: absolute;
border-radius: inherit;
background-color: currentColor;
28 changes: 28 additions & 0 deletions packages/pigment-react/tests/styled/fixtures/styled.output.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
@keyframes r1419f2q {
from {
transform: rotate(360deg);
}
to {
transform: rotate(0deg);
}
}
.c1vtarpi {
color: red;
animation: r1419f2q 2s ease-out 0s infinite;
}
.s1sjy0ja {
display: none;
position: absolute;
border-radius: inherit;
background-color: currentColor;
opacity: 0.38;
font-size: 3rem;
}
.s1sjy0ja-1 {
font-size: 3rem;
}
.s6hrafw {
display: block;
opacity: 0.38;
font-size: 3rem;
}
16 changes: 16 additions & 0 deletions packages/pigment-react/tests/styled/fixtures/styled.output.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { styled as _styled3 } from '@pigment-css/react';
import { styled as _styled2 } from '@pigment-css/react';
import { styled as _styled } from '@pigment-css/react';
import _theme from '@pigment-css/react/theme';
const Component = /*#__PURE__*/ _styled('div')({
classes: ['c1vtarpi'],
});
const SliderRail = /*#__PURE__*/ _styled2('span', {
name: 'MuiSlider',
slot: 'Rail',
})({
classes: ['s1sjy0ja', 's1sjy0ja-1'],
});
const SliderRail2 = /*#__PURE__*/ _styled3('span')({
classes: ['s6hrafw'],
});
40 changes: 40 additions & 0 deletions packages/pigment-react/tests/styled/styled.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import path from 'node:path';
import { runTransformation, expect } from '../testUtils';

const theme = {
palette: {
primary: {
main: 'red',
},
},
size: {
font: {
h1: '3rem',
},
},
components: {
MuiSlider: {
styleOverrides: {
rail: {
fontSize: '3rem',
},
},
},
},
};

describe('Pigment CSS - styled', () => {
it('basics', async () => {
const { output, fixture } = await runTransformation(
path.join(__dirname, 'fixtures/styled.input.js'),
{
themeArgs: {
theme,
},
},
);

expect(output.js).to.equal(fixture.js);
expect(output.css).to.equal(fixture.css);
});
});
91 changes: 91 additions & 0 deletions packages/pigment-react/tests/testUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import { expect as chaiExpect } from 'chai';
import { asyncResolveFallback } from '@wyw-in-js/shared';
import { TransformCacheCollection, transform, createFileReporter } from '@wyw-in-js/transform';
import { preprocessor } from '@pigment-css/react/utils';
import * as prettier from 'prettier';

const shouldUpdateOutput = process.env.UPDATE_FIXTURES === 'true';

export async function runTransformation(
absolutePath: string,
options?: { themeArgs?: { theme?: any } },
) {
const cache = new TransformCacheCollection();
const { emitter: eventEmitter } = createFileReporter(false);
const inputFilePath = absolutePath;
const outputFilePath = absolutePath.replace('.input.', '.output.');
const outputCssFilePath = absolutePath.replace('.input.js', '.output.css');

const inputContent = fs.readFileSync(inputFilePath, 'utf8');
let outputContent = fs.existsSync(outputFilePath) ? fs.readFileSync(outputFilePath, 'utf8') : '';
let outputCssContent = fs.existsSync(outputCssFilePath)
? fs.readFileSync(outputCssFilePath, 'utf8')
: '';

const pluginOptions = {
themeArgs: {
theme: options?.themeArgs?.theme,
},
babelOptions: {
configFile: false,
babelrc: false,
},
tagResolver(_source: string, tag: string) {
return require.resolve(`../exports/${tag}`);
},
};
const result = await transform(
{
options: {
filename: inputFilePath,
preprocessor,
pluginOptions,
},
cache,
eventEmitter,
},
inputContent,
asyncResolveFallback,
);

const prettierConfig = await prettier.resolveConfig(
path.join(process.cwd(), 'prettier.config.js'),
);
const formattedJs = await prettier.format(result.code, {
...prettierConfig,
parser: 'babel',
});
const formattedCss = await prettier.format(result.cssText ?? '', {
...prettierConfig,
parser: 'css',
});

if (!outputContent || shouldUpdateOutput) {
fs.writeFileSync(outputFilePath, formattedJs, 'utf-8');
outputContent = formattedJs;
}

if (!outputCssContent || shouldUpdateOutput) {
fs.writeFileSync(outputCssFilePath, formattedCss, 'utf-8');
outputCssContent = formattedCss;
}

return {
output: {
js: formattedJs,
css: formattedCss,
},
fixture: {
js: outputContent,
css: outputCssContent,
},
};
}

export function expect(val: any): ReturnType<typeof chaiExpect> {
const CUSTOM_ERROR =
'The file contents have changed. Run "test:update" command to update the file if this is expected.';
return chaiExpect(val, CUSTOM_ERROR);
}
3 changes: 2 additions & 1 deletion packages/pigment-react/tsconfig.json
Original file line number Diff line number Diff line change
@@ -12,7 +12,8 @@
"@mui/system/*": ["./packages/mui-system/src/*"],
"@mui/utils": ["./packages/mui-utils/src"],
"@mui/utils/*": ["./packages/mui-utils/src/*"]
}
},
"types": ["node", "mocha"]
},
"include": ["src/**/*.ts"],
"exclude": ["./tsup.config.ts"]
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

0 comments on commit 230b282

Please sign in to comment.