grut v0.2.1
grut
/gru:t/
Generator of React Unit Tests based on fixtures and test templates
was made during the Catawiki Hackathon 2021
An opinionated unit test generator for React based on fixtures. This project was created during the Catawiki Hackathon 2021 by @sseletskyy and @alcidesqueiroz, therefore, it's not (yet) suitable for production and still has lots of things to be improved.
How to use
Install grut
npm i -D grut
yarn add -D grut
Create a fixture file
See details below
Run grut
npx grut
yarn grut
Update grut configuration in package.json
yarn grut
will add grut
section in your project's package.json
{
...
"grut": {
"fixturesPath": "src"
}
}
Update the relative path fixturePath
according to your project configuration.
Check generated files near fixture files
The name of a generated test file is:
<FixtureName>-<fixtureObjectKey>.generated.spec.tsx
How to write a fixture file
Create a *.fixture.js
file nearby your React component.
The file should export the JS plain object in an old-fashioned way
const fixtures = {
...
}
module.exports = {
default: fixtures,
};
The fixtures
object should contain at least one fixture
object with an arbitrary name.
The structure of the fixture:
interface Fixture {
component: string; // import statement for React component
props: Record<string, any>; // props for React component
declarations: Declaration[]; // array of declarations, each declaration generates a unit test
}
type Declaration = Record<string, any>;
Example of the React component.
// file: src/example/ProductList.jsx
const ProductList = ({list}) => (
<div>
{list.map((item, index) => <div key={index} className="itemElement">{item}</div>)}
</div>
)
export default ProductList
Example of the fixture file
// file: src/example/__tests__/ProductList.fixture.js
const fixtures = {
listOfThree: {
component: `import SpecComponent from '../ProductList.jsx'`,
props: {
items: ['apricot', 'banana', 'carrot']
},
spdt: [
{ checkSelector: '.itemElement', length: 3 }, // <----
]
}
}
module.exports = {
default: fixtures,
};
You can add as many fixture objects as you need
// file: src/example/__tests__/ProductList.fixture.js
const fixtures = {
listOfThree: {
component: `import SpecComponent from '../ProductList.jsx'`,
props: {
items: ['apricot', 'banana', 'carrot']
},
spdt: [
{ checkSelector: '.itemElement', length: 3 }, // <----
]
},
listOfTwo: {
component: `import SpecComponent from '../ProductList.jsx'`,
props: {
items: ['banana', 'carrot']
},
spdt: [
{ checkSelector: '.itemElement', length: 2 }, // <----
]
}
}
module.exports = {
default: fixtures,
};
For the second example with two fixture objects grut
will generate two test files:
ProductList-listOfThree.generated.spec.tsx
ProductList-listOfTwo.generated.spec.tsx
Development mode
Before running tests install peer dependencies locally by running
npm run peers
or
npx npm-install-peers
or
yarn peers