You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
var ReactTestUtils =require('react-dom/test-utils'); // ES5 with npm
13
+
var ReactTestUtils =require('react-dom/test-utils'); // ES5 с npm
14
14
```
15
15
16
-
## Overview {#overview}
16
+
## Обзор {#overview}
17
17
18
-
`ReactTestUtils`makes it easy to test React components in the testing framework of your choice. At Facebook we use[Jest](https://facebook.github.io/jest/)for painless JavaScript testing. Learn how to get started with Jest through the Jest website's [React Tutorial](https://jestjs.io/docs/tutorial-react).
18
+
`ReactTestUtils`позволяет легко тестировать React-компоненты в любом тестовом фреймворке на ваш выбор. В Facebook мы используем[Jest](https://facebook.github.io/jest/)для гладкого тестирования JavaScript-кода. Если хотите обучится Jest, ознакомьтесь с [руководством по React](https://jestjs.io/docs/en/tutorial-react).
19
19
20
-
> Note:
20
+
> Примечание:
21
21
>
22
-
> We recommend using [`react-testing-library`](https://git.io/react-testing-library) which is designed to enable and encourage writing tests that use your components as the end users do.
22
+
> Мы рекомендуем использовать библиотеку [`react-testing-library`](https://git.io/react-testing-library), которая значительно облегчает написание тестов, имитируя поведение пользователей вашего приложения в браузере, и просто побуждает к хорошим практикам в тестировании.
23
23
>
24
-
> Alternatively, Airbnb has released a testing utility called [Enzyme](https://airbnb.io/enzyme/), which makes it easy to assert, manipulate, and traverse your React Components' output.
24
+
> В качестве альтернативы, Airbnb выпустил утилиту тестирования [Enzyme](https://airbnb.io/enzyme/), которая легко позволяет делать проверки, управлять, а также просматривать выходные данные React-компонентов.
25
25
26
26
-[`act()`](#act)
27
27
-[`mockComponent()`](#mockcomponent)
@@ -40,17 +40,17 @@ var ReactTestUtils = require('react-dom/test-utils'); // ES5 with npm
40
40
-[`renderIntoDocument()`](#renderintodocument)
41
41
-[`Simulate`](#simulate)
42
42
43
-
## Reference {#reference}
43
+
## Справочник {#reference}
44
44
45
45
### `act()` {#act}
46
46
47
-
To prepare a component for assertions, wrap the code rendering it and performing updates inside an `act()` call. This makes your test run closer to how React works in the browser.
47
+
Чтобы подготовить компонент для тестирования, оберните код с рендерингом и выполнением обновлений внутри функции `act()`. Это сделает код теста для компонентов React более близким к тому, как он рендерится в браузере.
48
48
49
-
>Note
49
+
>Примечание:
50
50
>
51
-
>If you use `react-test-renderer`, it also provides an `act` export that behaves the same way.
51
+
>Если вы используете пакет `react-test-renderer`, то он также предоставляет функцию `act`, которая работает аналогичным образом.
52
52
53
-
For example, let's say we have this `Counter` component:
53
+
Допустим, у нас есть компонент `Counter`:
54
54
55
55
```js
56
56
classAppextendsReact.Component {
@@ -60,10 +60,10 @@ class App extends React.Component {
expect(label.textContent).toBe('Вы нажали на кнопку 1 раз');
121
+
expect(document.title).toBe('Вы нажали на кнопку 1 раз');
122
122
});
123
123
```
124
124
125
-
Don't forget that dispatching DOM events only works when the DOM container is added to the `document`. You can use a helper like [`react-testing-library`](https://github.com/kentcdodds/react-testing-library) to reduce the boilerplate code.
125
+
Не забывайте, что отправка DOM-событий работает только если DOM-контейнер добавлен в `document`. Можно использовать вспомогательную библиотеку [`react-testing-library`](https://github.com/kentcdodds/react-testing-library), чтобы уменьшить количество шаблонного кода.
126
126
127
127
* * *
128
128
@@ -135,11 +135,11 @@ mockComponent(
135
135
)
136
136
```
137
137
138
-
Pass a mocked component module to this method to augment it with useful methods that allow it to be used as a dummy React component. Instead of rendering as usual, the component will become a simple `<div>` (or other tag if `mockTagName` is provided) containing any provided children.
138
+
Передайте фиктивный модуль компонента этому методу, чтобы дополнить его полезными методами, которые позволяют использовать его в качестве фиктивного компонента React. Вместо того чтобы рендерить как обычно, компонент становится простым элементом `<div>` (или другим тегом `mockTagName`, если указан), содержащий любые предоставленные дочерние элементы.
139
139
140
-
> Note:
140
+
> Примечание:
141
141
>
142
-
> `mockComponent()`is a legacy API. We recommend using [shallow rendering](/docs/shallow-renderer.html)or[`jest.mock()`](https://facebook.github.io/jest/docs/en/tutorial-react-native.html#mock-native-modules-using-jestmock) instead.
142
+
> API-метод `mockComponent()`объявлен устаревшим. Поэтому вместо него рекомендуется использоваться [поверхностный рендеринг](/docs/shallow-renderer.html)или[`jest.mock()`](https://facebook.github.io/jest/docs/en/tutorial-react-native.html#mock-native-modules-using-jestmock).
143
143
144
144
* * *
145
145
@@ -149,7 +149,7 @@ Pass a mocked component module to this method to augment it with useful methods
Returns`true` if`element`is a React element whose type is of a React `componentClass`.
165
+
Возвращает`true`, если`element`является элементом React, тип которого имеет тип React `componentClass`.
166
166
167
167
* * *
168
168
@@ -172,7 +172,7 @@ Returns `true` if `element` is a React element whose type is of a React `compone
172
172
isDOMComponent(instance)
173
173
```
174
174
175
-
Returns`true` if`instance`is a DOM component (such as a `<div>`or`<span>`).
175
+
Возвращает`true`, если`instance`является DOM-компонентом (таким как `<div>`или`<span>`).
176
176
177
177
* * *
178
178
@@ -182,7 +182,7 @@ Returns `true` if `instance` is a DOM component (such as a `<div>` or `<span>`).
182
182
isCompositeComponent(instance)
183
183
```
184
184
185
-
Returns`true` if`instance`is a user-defined component, such as a class or a function.
185
+
Возвращает`true`, если`instance`является пользовательским компонентом, определённым как класс или функция.
186
186
187
187
* * *
188
188
@@ -195,7 +195,7 @@ isCompositeComponentWithType(
195
195
)
196
196
```
197
197
198
-
Returns`true` if`instance`is a component whose type is of a React `componentClass`.
198
+
Возвращает`true`, если`instance`является компонентом, который имеет тип React `componentClass`.
199
199
200
200
* * *
201
201
@@ -208,7 +208,7 @@ findAllInRenderedTree(
208
208
)
209
209
```
210
210
211
-
Traverse all components in `tree` and accumulate all components where `test(component)`is`true`. This is not that useful on its own, but it's used as a primitive for other test utils.
211
+
Находит все компоненты в дереве `tree`, для которых `test(component)`возвращает`true`. Сам по себе он не так полезен, но используется как примитив для других тестовых утилит.
Like [`scryRenderedDOMComponentsWithClass()`](#scryrendereddomcomponentswithclass) but expects there to be one result, and returns that one result, or throws exception if there is any other number of matches besides one.
237
+
Работает как [`scryRenderedDOMComponentsWithClass()`](#scryrendereddomcomponentswithclass), но ожидает, что найдётся ровно один результат, который и будет возвращён. Если ничего не будет найдено или найдётся больше одного результата, генерирует исключение.
Like [`scryRenderedDOMComponentsWithTag()`](#scryrendereddomcomponentswithtag)but expects there to be one result, and returns that one result, or throws exception if there is any other number of matches besides one.
263
+
Также как [`scryRenderedDOMComponentsWithTag()`](#scryrendereddomcomponentswithtag)но ожидает, что найдётся ровно один результат, который и будет возвращён. Если ничего не будет найдено или найдётся больше одного результата, генерирует исключение.
Same as [`scryRenderedComponentsWithType()`](#scryrenderedcomponentswithtype) but expects there to be one result and returns that one result, or throws exception if there is any other number of matches besides one.
289
+
Работает так же как [`scryRenderedComponentsWithType()`](#scryrenderedcomponentswithtype), но ожидает, что найдётся ровно один результат, который и будет возвращён. Если ничего не будет найдено или найдётся больше одного результата, генерирует исключение.
290
290
291
291
***
292
292
@@ -296,20 +296,20 @@ Same as [`scryRenderedComponentsWithType()`](#scryrenderedcomponentswithtype) bu
296
296
renderIntoDocument(element)
297
297
```
298
298
299
-
Render a React element into a detached DOM node in the document. **This function requires a DOM.**It is effectively equivalent to:
299
+
Отображает React элемент в отдельно взятом DOM-узле документа. **Этой функции нужен DOM.**Это фактически эквивалентно:
300
300
301
301
```js
302
302
constdomContainer=document.createElement('div');
303
303
ReactDOM.render(element, domContainer);
304
304
```
305
305
306
-
> Note:
306
+
> Примечание:
307
307
>
308
-
> You will need to have `window`, `window.document`and`window.document.createElement`globally available **before**you import `React`. Otherwise React will think it can't access the DOM and methods like `setState`won't work.
308
+
> `window`, `window.document`и`window.document.createElement`должны быть доступными **перед**тем как вы импортируете `React`. В противном случае React будет думать что не может получить доступ к DOM и такие методы как `setState`не будут работать.
309
309
310
310
* * *
311
311
312
-
## Other Utilities {#other-utilities}
312
+
## Другие утилиты {#other-utilities}
313
313
314
314
### `Simulate` {#simulate}
315
315
@@ -320,30 +320,30 @@ Simulate.{eventName}(
320
320
)
321
321
```
322
322
323
-
Simulate an event dispatch on a DOM node with optional`eventData` event data.
323
+
Симулировать отправку события сработавшего на DOM-узле с дополнительным объектом`eventData`.
324
324
325
-
`Simulate`has a method for [every event that React understands](/docs/events.html#supported-events).
325
+
`Simulate`имеет метод для [каждого события, которое React может понимать](/docs/events.html#supported-events).
> You will have to provide any event property that you're using in your component (e.g. keyCode, which, etc...) as React is not creating any of these for you.
347
+
> Вам нужно будет предоставить все свойства события, которое вы используете в своём компоненте (например, keyCode, which и т.д.), поскольку React не создаёт ничего из этого.
0 commit comments