https://github.com/dusanjovanov/react-use-test
⚗️ Hook for testing React component state and functions
https://github.com/dusanjovanov/react-use-test
hook react testing
Last synced: over 1 year ago
JSON representation
⚗️ Hook for testing React component state and functions
- Host: GitHub
- URL: https://github.com/dusanjovanov/react-use-test
- Owner: dusanjovanov
- License: mit
- Created: 2022-05-08T21:15:03.000Z (about 4 years ago)
- Default Branch: master
- Last Pushed: 2022-05-08T21:16:21.000Z (about 4 years ago)
- Last Synced: 2025-02-28T04:59:23.875Z (over 1 year ago)
- Topics: hook, react, testing
- Language: TypeScript
- Homepage:
- Size: 129 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README

⚗️ Hook for testing React component state and functions
[](https://www.npmjs.com/package/react-use-test)
## **Installation**
```bash
npm install react-use-test
```
```bash
yarn add react-use-test
```
> With standard React testing (@testing-library/react) you don't have access to the internals of React components (state, functions, refs etc.). This hook aims to solve that.
> The hook only supports the Jest framework for now.
## **Usage**
```tsx
// call useTest in your component and pass it the action and observe functions
import { useTest } from 'react-use-test';
const Counter = () => {
const [count, setCount] = React.useState(0);
const increment = () => setCount(count + 1);
// useTest only executes it's code in the jest environment
useTest(
done => {
increment();
// call done when you're done preparing for the test
done();
},
() => {
// jest provides expect as a global function
expect(count).toBe(1);
}
);
return (
{count}
+
);
};
// then inside your test file
import { render } from '@testing-library/react';
import { Counter } from '../components/Counter';
// if something throws an error inside useTest, the test will fail
it('Counter', () => {
render();
});
// this library also exports a helper for simulating a change event on inputs
import { fireChangeEvent } from 'react-use-test';
export const TextField = () => {
const [value, setValue] = React.useState('');
useTest(
done => {
const element = document.getElementById('text');
if (element) {
fireChangeEvent(element, 'some text');
done();
}
},
() => {
expect(value).toBe('some text');
}
);
return (
setValue(e.target.value)}
/>
);
};
```
## **Usage with Typescript**
You need to declare the `expect` global somewhere in your application code like this
```tsx
declare var expect: any;
```