|
| 1 | +--- |
| 2 | +sidebar_position: 3 |
| 3 | +--- |
| 4 | + |
| 5 | +# Jest testing guide |
| 6 | + |
| 7 | +## Setting up a mock |
| 8 | + |
| 9 | +This library includes a built in mock for Jest. To use it, add the following code to the [jest setup](https://jestjs.io/docs/configuration#setupfiles-array) file: |
| 10 | + |
| 11 | +```js |
| 12 | +jest.mock('react-native-keyboard-controller', () => |
| 13 | + require('react-native-keyboard-controller/jest') |
| 14 | +); |
| 15 | +``` |
| 16 | + |
| 17 | +## Test case example |
| 18 | + |
| 19 | +Once you've set up mock - you can write your first test 😊. A sample of test case is shown below. For more test cases please see [this](https://github.com/kirillzyusko/react-native-keyboard-controller/tree/main/example/__tests__) link. |
| 20 | + |
| 21 | +```tsx |
| 22 | +import '@testing-library/jest-native/extend-expect'; |
| 23 | +import React from 'react'; |
| 24 | +import { Animated } from 'react-native'; |
| 25 | +import { render } from '@testing-library/react-native'; |
| 26 | + |
| 27 | +import { useKeyboardAnimation } from 'react-native-keyboard-controller'; |
| 28 | + |
| 29 | +function TestComponent() { |
| 30 | + const { height } = useKeyboardAnimation(); |
| 31 | + |
| 32 | + return ( |
| 33 | + <Animated.View |
| 34 | + testID="view" |
| 35 | + style={{ transform: [{ translateY: height }] }} |
| 36 | + /> |
| 37 | + ); |
| 38 | +} |
| 39 | + |
| 40 | +describe('basic keyboard interaction', () => { |
| 41 | + it('should have different styles depends on position', () => { |
| 42 | + const { getByTestId, update } = render(<TestComponent />); |
| 43 | + |
| 44 | + expect(getByTestId('view')).toHaveStyle({ transform: [{ translateY: 0 }] }); |
| 45 | + |
| 46 | + (useKeyboardAnimation as jest.Mock).mockReturnValue({ |
| 47 | + height: new Animated.Value(150), |
| 48 | + progress: new Animated.Value(0.5), |
| 49 | + }); |
| 50 | + update(<TestComponent />); |
| 51 | + |
| 52 | + expect(getByTestId('view')).toHaveStyle({ |
| 53 | + transform: [{ translateY: 150 }], |
| 54 | + }); |
| 55 | + |
| 56 | + (useKeyboardAnimation as jest.Mock).mockReturnValue({ |
| 57 | + height: new Animated.Value(300), |
| 58 | + progress: new Animated.Value(1), |
| 59 | + }); |
| 60 | + update(<TestComponent />); |
| 61 | + |
| 62 | + expect(getByTestId('view')).toHaveStyle({ |
| 63 | + transform: [{ translateY: 300 }], |
| 64 | + }); |
| 65 | + }); |
| 66 | +}); |
| 67 | +``` |
0 commit comments