react-shallow-search

react-shallow-search

NPM dependencies status

Test utils for searching elements in the react tree

Api reference

import assert from 'node:assert';
import { createRenderer } from 'react-test-renderer/shallow';
import { get } from 'react-shallow-search';

function MyComponent() {
return (
<main>
<div>
<span className="target">
Test
</span>
</div>
</main>
);
}

const renderer = createRenderer();
renderer.render(<MyComponent />);
const result = renderer.getRenderOutput();

const targetSpan = get(result, {
className: 'target',
});

assert.strictEqual(targetSpan.type, 'span');
assert.strictEqual(targetSpan.props.children, 'Test');

Installation

yarn add react-shallow-search react-is --dev

Examples

Search by type of react element

import { get } from 'react-shallow-search';

get(
<MyComponent>
Test
</MyComponent>,
{
component: MyComponent,
},
);

Search by className

import { get } from 'react-shallow-search';

get(
<MyComponent className="foo bar baz">
Test
</MyComponent>,
{
className: 'bar',
},
);

Search by props

import { get } from 'react-shallow-search';

get(
<MyComponent
foo="bar"
baz={123}
>
Test
</MyComponent>,
{
props: {
foo: 'bar',
baz: 123,
},
},
);

Get props of element

import assert from 'node:assert';
import { getProps } from 'react-shallow-search';

const componentProps = getProps(
<MyComponent
foo="bar"
baz={123}
abc="def"
>
Test
</MyComponent>,
{
props: {
foo: 'bar',
baz: 123,
},
},
);

assert.strictEqual(componentProps.abc, 'def');

Custom attribute with children

import { defaultGetChildren, get } from 'react-shallow-search';

get(
<ExoticComponent
block={(
<span className="target">
Test
</span>
)}
/>,
{
className: 'target',
},
{
getChildren: (element) => {
if (element.type === ExoticComponent) {
return [element.block];
}

return defaultGetChildren(element);
},
},
);

Custom matching function

import { defaultMatch, get } from 'react-shallow-search';

get(
<ExoticComponent
customClassName="target"
/>,
{
className: 'target',
},
{
match: (element, query) => {
if (element.type === ExoticComponent) {
return element.props.customClassName.split(' ').includes(query.className);
}

return defaultMatch(element, query);
},
},
);

Search for multiple elements

import { getAll } from 'react-shallow-search';

getAll(
<div>
<div className="foo">Bar</div>
<div className="foo">Bar</div>
<div className="foo">Bar</div>
</div>,
{
className: 'foo',
},
);

Search for element that can be not rendered

  • get -> query
  • getAll -> queryAll

Create an object of utilities

import { createAccessors } from 'react-shallow-search';

const {
get,
getProps,
getAll,
query,
queryAll,
} = createAccessors(
<div>
{condition && (
<div className="foo">Bar</div>
)}
</div>,
{
className: 'foo',
},
);

Generated using TypeDoc