greenkeeper[bot] d2e00f5264 Update dependencies to enable Greenkeeper 🌴 (#14)
Let’s get started with automated dependency management for react-native-testing-library 💪

🔒 Greenkeeper has found a `yarn.lock` file in this repository. Greenkeeper supports lockfile updates for public packages. If you use private packages in your repository, please use [greenkeeper-lockfile](https://github.com/greenkeeperio/greenkeeper-lockfile) to make sure these can get updated as well.

This pull request **updates all your dependencies to their latest version**. Having them all up to date really is the best starting point for keeping up with new releases. Greenkeeper will look out for further dependency updates and make sure to handle them in isolation and in real-time, but only after **you merge this pull request**.

**Important: Greenkeeper will only start watching this repository’s dependency updates after you merge this initial pull request**.





---
<details>
<summary>🏷 How to check the status of this repository</summary>

Greenkeeper adds a badge to your README which indicates the status of this repository.

This is what your badge looks like right now 👉  ![Greenkeeper badge](https://badges.greenkeeper.io/callstack/react-native-testing-library.svg)
</details>
<details>
<summary>🙈 How to ignore certain dependencies</summary>

You may have good reasons for not wanting to update to a certain dependency right now. In this case, you can [change the dependency’s version string in the `package.json` file back to whatever you prefer](https://github.com/callstack/react-native-testing-library/edit/greenkeeper/initial/package.json).

To make sure Greenkeeper doesn’t nag you again on the next update, add a `greenkeeper.ignore` field to your `package.json`, containing a list of dependencies you don’t want to update.

```js
// package.json
{
  …
  "greenkeeper": {
    "ignore": [
      "package-names",
      "you-want-me-to-ignore"
    ]
  }
}
```
</details>
<details>
<summary>👩‍💻 How to update this pull request</summary>

```bash
  # Change into your repository’s directory
  git fetch --all
  git checkout greenkeeper/initial
  npm install-test
  # Adapt your code until everything works again
  git commit -m 'chore: adapt code to updated dependencies'
  git push https://github.com/callstack/react-native-testing-library.git greenkeeper/initial
```
</details>
<details>
<summary>✨ How do dependency updates work with Greenkeeper?</summary>

After you merge this pull request, **Greenkeeper will create a new branch whenever a  dependency is updated**, with the new version applied. The branch creation should trigger your testing services and check whether your code still works with the new dependency version. Depending on the the results of these tests Greenkeeper will try to open meaningful and helpful pull requests and issues, so your dependencies remain working and up-to-date.

```diff
-  "underscore": "^1.6.0"
+  "underscore": "^1.7.0"
```

The above example shows an in-range update. `1.7.0` is included in the old `^1.6.0` range, because of the [caret `^` character ](https://docs.npmjs.com/misc/semver#ranges).
When the test services report success Greenkeeper will silently delete the branch again, because no action needs to be taken – everything is fine.

However, should the tests fail, Greenkeeper will create an issue to inform you about the problem immediately.

This way, you’ll never be surprised by a dependency breaking your code. As long as everything still works, Greenkeeper will stay out of your way, and as soon as something goes wrong, you’ll be the first to know.

```diff
-  "lodash": "^3.0.0"
+  "lodash": "^4.0.0"
```

In this example, the new version `4.0.0` is _not_ included in the old `^3.0.0` range.
For version updates like these – let’s call them “out of range” updates – you’ll receive a pull request.

This means that **you no longer need to check for new versions manually** – Greenkeeper will keep you up to date automatically.

These pull requests not only serve as reminders to update: If you have solid tests and good coverage, and the pull requests passes those tests, you can very likely just merge it and release a new version of your software straight away :shipit:

To get a better idea of which ranges apply to which releases, check out the extremely useful [semver calculator](https://semver.npmjs.com/) provided by npm.
</details>
<details>
<summary>FAQ and help</summary>

There is a collection of [frequently asked questions](https://greenkeeper.io/faq.html). If those don’t help, you can always [ask the humans behind Greenkeeper](https://github.com/greenkeeperio/greenkeeper/issues/new).
</details>


---

Good luck with your project and see you soon ✨

Your [Greenkeeper](https://greenkeeper.io) bot 🌴
2018-10-07 11:40:29 +02:00
2018-10-06 19:25:51 +02:00
2018-10-06 19:30:24 +02:00
2018-10-01 18:15:56 +02:00
2018-10-07 10:59:27 +02:00
2018-10-01 18:15:56 +02:00
2018-10-01 18:15:56 +02:00
2018-10-06 19:25:51 +02:00
2018-10-06 19:25:51 +02:00
2018-10-07 11:03:14 +02:00
2018-10-01 16:32:14 +02:00

react-native-testing-library

Simple React Native testing utilities helping you write better tests with less effort

Build Status Version MIT License PRs Welcome Chat Greenkeeper badge

Appreciation notice: This project is heavily inspired by react-testing-library. Go check it out and use it to test your web React apps.

The problem

You want to write maintainable tests for your React Native components without testing implementation details, but then you're told to use Enzyme, which only supports shallow rendering in React Native environment. And you want to render deep! But doing so with react-test-renderer is so painful.

You would also like to use the newest React features, but you need to wait for your testing library's abstractions to catch up and it takes a while.

This solution

The react-native-testing-library is a lightweight solution for testing your React Native components. It provides light utility functions on top of react-test-renderer letting you always be up to date with latest React features and write any component tests you like, be it shallow or deeply rendered ones. But really not any, it prevents you from testing implementation details because we stand this is a very bad practice.

This library is a replacement for Enzyme.

Example

import { render, fireEvent } from 'react-native-testing-library';
import { QuestionsBoard } from '../QuestionsBoard';

function setAnswer(question, answer) {
  fireEvent.changeText(question, answer);
}

test('should verify two questions', () => {
  const { getAllByName, getByText } = render(<QuestionsBoard {...props} />);
  const allQuestions = getAllByName('Question');

  setAnswer(allQuestions[0], 'a1');
  setAnswer(allQuestions[1], 'a2');

  fireEvent.press(getByText('submit'));

  expect(props.verifyQuestions).toBeCalledWith({
    '1': { q: 'q1', a: 'a1' },
    '2': { q: 'q2', a: 'a2' },
  });
});

Installation

Open a Terminal in your project's folder and run:

yarn add --dev react-native-testing-library

This library has a peerDependencies listing for react-test-renderer, pretty-format and, of course, react. Make sure to install them too!

As you may have noticed, it's not tied to React Native at all – you can safely use it in your React components if you feel like not interacting directly with DOM.

Usage

render

Defined as:

function render(
  component: React.Element<*>,
  options?: {
    /* You won't often use this, but it's helpful when testing refs */
    createNodeMock: (element: React.Element<*>) => any,
  }
): RenderResult {}

Deeply render given React element and returns helpers to query the output. For convenience it also returns react-test-renderer's instance and renderer objects, in case you need more control.

import { render } from 'react-native-testing-library';

const { getByTestId, getByName /*...*/ } = render(<Component />);

Returns a RenderResult object with following properties:

getByTestId: (testID: string)

A method returning a ReactTestInstance with matching testID prop. Throws when no matches.

Note: most methods like this one return a ReactTestInstance with following properties that you may be interested in:

type ReactTestInstance = {
  type: string | Function,
  props: { [propName: string]: any },
  parent: null | ReactTestInstance,
  children: Array<ReactTestInstance | string>,
};

getByName: (name: string | React.Element<*>)

A method returning a ReactTestInstance with matching name – may be a string or React Element. Throws when no matches.

getAllByName: (name: string | React.Element<*>)

A method returning an array of ReactTestInstances with matching name – may be a string or React Element.

getByText: (text: string | RegExp)

A method returning a ReactTestInstance with matching text – may be a string or regular expression. Throws when no matches.

getAllByText: (text: string | RegExp)

A method returning an array of ReactTestInstances with matching text – may be a string or regular expression.

getByProps: (props: { [propName: string]: any })

A method returning a ReactTestInstance with matching props object. Throws when no matches.

getAllByProps: (props: { [propName: string]: any })

A method returning an array of ReactTestInstances with matching props object.

update: (element: React.Element<*>) => void

Re-render the in-memory tree with a new root element. This simulates a React update at the root. If the new element has the same type and key as the previous element, the tree will be updated; otherwise, it will re-mount a new tree.

unmount: () => void

Unmount the in-memory tree, triggering the appropriate lifecycle events

When using React context providers, like Redux Provider, you'll likely want to wrap rendered component with them. In such cases it's convenient to create your custom render method. Follow this great guide on how to set this up.

shallow

Shallowly render given React copmonent. Since it doesn't return helpers to query the output, it's mostly adviced to used for snapshot testing (short snapshots are best for code reviewers).

import { shallow } from 'react-native-testing-library';

test('Component has a structure', () => {
  const { output } = shallow(<Component />);
  expect(output).toMatchSnapshot();
});

FireEvent API

fireEvent: (element: ReactTestInstance, eventName: string, data?: *) => void

Invokes named event handler on the element or parent element in the tree.

import { View } from 'react-native';
import { render, fireEvent } from 'react-native-testing-library';
import { MyComponent } from './MyComponent';

const onEventMock = jest.fn();
const { getByTestId } = render(
  <MyComponent testID="custom" onMyCustomEvent={onEventMock} />
);

fireEvent(getByTestId('custom'), 'myCustomEvent');

fireEvent.press: (element: ReactTestInstance) => void

Invokes press event handler on the element or parent element in the tree.

import { View, Text, TouchableOpacity } from 'react-native';
import { render, fireEvent } from 'react-native-testing-library';

const onPressMock = jest.fn();

const { getByTestId } = render(
  <View>
    <TouchableOpacity onPress={onPressMock} testID="button">
      <Text>Press me</Text>
    </TouchableOpacity>
  </View>
);

fireEvent.press(getByTestId('button'));

fireEvent.doublePress: (element: ReactTestInstance) => void

Invokes doublePress event handler on the element or parent element in the tree.

import { TouchableOpacity, Text } from 'react-native';
import { render, fireEvent } from 'react-native-testing-library';

const onDoublePressMock = jest.fn();

const { getByTestId } = render(
  <TouchableOpacity onDoublePress={onDoublePressMock}>
    <Text testID="button-text">Click me</Text>
  </TouchableOpacity>
);

fireEvent.doublePress(getByTestId('button-text'));

fireEvent.changeText: (element: ReactTestInstance, data?: *) => void

Invokes changeText event handler on the element or parent element in the tree.

import { View, TextInput } from 'react-native';
import { render, fireEvent } from 'react-native-testing-library';

const onChangeTextMock = jest.fn();
const CHANGE_TEXT = 'content';

const { getByTestId } = render(
  <View>
    <TextInput testID="text-input" onChangeText={onChangeTextMock} />
  </View>
);

fireEvent.changeText(getByTestId('text-input'), CHANGE_TEXT);

fireEvent.scroll: (element: ReactTestInstance, data?: *) => void

Invokes scroll event handler on the element or parent element in the tree.

import { ScrollView, TextInput } from 'react-native';
import { render, fireEvent } from 'react-native-testing-library';

const onScrollMock = jest.fn();
const eventData = {
  nativeEvent: {
    contentOffset: {
      y: 200,
    },
  },
};

const { getByTestId } = render(
  <ScrollView testID="scroll-view" onScroll={onScrollMock}>
    <Text>XD</Text>
  </ScrollView>
);

fireEvent.scroll(getByTestId('scroll-view'), eventData);

debug

Log prettified shallowly rendered component or test instance (just like snapshot) to stdout.

import { debug } from 'react-native-testing-library';

debug(<Component />);
// console.log:
// <View>
//   <Text>Component</Text>
// </View>

flushMicrotasksQueue

Wait for microtasks queue to flush. Useful if you want to wait for some promises with async/await.

import { flushMicrotasksQueue, render } from 'react-native-testing-library';

test('fetch data', async () => {
  const { getByText } = render(<FetchData />);
  getByText('fetch');
  await flushMicrotasksQueue();
  expect(getByText('fetch').props.title).toBe('loaded');
});

query APIs

Each of the get APIs listed in the render section above have a complimentary query API. The get APIs will throw errors if a proper node cannot be found. This is normally the desired effect. However, if you want to make an assertion that an element is not present in the hierarchy, then you can use the query API instead:

import { render } from 'react-native-testing-library';

const { queryByText } = render(<Form />);
const submitButton = queryByText('submit');
expect(submitButton).toBeNull(); // it doesn't exist

queryAll APIs

Each of the query APIs have a corresponding queryAll version that always returns an Array of matching nodes. getAll is the same but throws when the array has a length of 0.

import { render } from 'react-native-testing-library';

const { queryAllByText } = render(<Forms />);
const submitButtons = queryAllByText('submit');
expect(submitButtons).toHaveLength(3); // expect 3 elements
S
Description
Write tests using React Native Testing Library (RNTL) v13 and v14 (@testing-library/react-native). Use when writing, reviewing, or fixing React Native…
Readme MIT 45 MiB
Languages
TypeScript 57.8%
MDX 39.6%
JavaScript 1.9%
CSS 0.7%