From edca929e981b1408b1a39d022a584c2163548345 Mon Sep 17 00:00:00 2001 From: Victor Rusakovich Date: Sat, 9 Mar 2019 00:54:02 +0200 Subject: [PATCH 01/33] Translate Test Renderer to Russian --- content/docs/reference-test-renderer.md | 78 ++++++++++++++++--------- 1 file changed, 49 insertions(+), 29 deletions(-) diff --git a/content/docs/reference-test-renderer.md b/content/docs/reference-test-renderer.md index 3de2d5752..01aa8e158 100644 --- a/content/docs/reference-test-renderer.md +++ b/content/docs/reference-test-renderer.md @@ -1,25 +1,25 @@ --- id: test-renderer -title: Test Renderer +title: Тестовый рендерер permalink: docs/test-renderer.html layout: docs category: Reference --- -**Importing** +**Импортирование** ```javascript import TestRenderer from 'react-test-renderer'; // ES6 const TestRenderer = require('react-test-renderer'); // ES5 with npm ``` -## Overview {#overview} +## Обзор {#overview} -This package provides a React renderer that can be used to render React components to pure JavaScript objects, without depending on the DOM or a native mobile environment. +В этом пакете вы найдете рендерер, который умеет рендерить React компоненты в простые JavaScript объекты, не используя при этом DOM или мобильное окружение. -Essentially, this package makes it easy to grab a snapshot of the platform view hierarchy (similar to a DOM tree) rendered by a React DOM or React Native component without using a browser or [jsdom](https://github.com/tmpvar/jsdom). +Собственно, пакет `react-test-renderer` облегчает возможность получения снимка дерева представления (чем-то похожего на DOM дерево) для текущей платформы. При этом не используются ни браузер, ни [jsdom](https://github.com/tmpvar/jsdom). -Example: +Пример: ```javascript import TestRenderer from 'react-test-renderer'; @@ -38,9 +38,9 @@ console.log(testRenderer.toJSON()); // children: [ 'Facebook' ] } ``` -You can use Jest's snapshot testing feature to automatically save a copy of the JSON tree to a file and check in your tests that it hasn't changed: [Learn more about it](https://facebook.github.io/jest/blog/2016/07/27/jest-14.html). +Jest может автоматически сохранять в файлы снимки с копией JSON-дерева, а затем проверять в тестах, чтобы ничего не поменялось: [узнать подробнее](https://facebook.github.io/jest/blog/2016/07/27/jest-14.html) -You can also traverse the output to find specific nodes and make assertions about them. +Также, есть возможность искать в дереве конкретные ноды и тестировать именно их: ```javascript import TestRenderer from 'react-test-renderer'; @@ -102,7 +102,8 @@ expect(testInstance.findByProps({className: "sub"}).children).toEqual(['Sub']); TestRenderer.create(element, options); ``` -Create a `TestRenderer` instance with the passed React element. It doesn't use the real DOM, but it still fully renders the component tree into memory so you can make assertions about it. The returned instance has the following methods and properties. +Создание экземпляра `TestRenderer` с переданным элементом React. Реальный DOM не будет использоваться - дерево компонентов будет полностью отрендерено в памяти и его можно будет тестировать. У созданного экземпляра `TestRenderer` будут пристутствовать следующие методы и свойства: + ### `testRenderer.toJSON()` {#testrenderertojson} @@ -110,7 +111,9 @@ Create a `TestRenderer` instance with the passed React element. It doesn't use t testRenderer.toJSON() ``` -Return an object representing the rendered tree. This tree only contains the platform-specific nodes like `
` or `` and their props, but doesn't contain any user-written components. This is handy for [snapshot testing](https://facebook.github.io/jest/docs/en/snapshot-testing.html#snapshot-testing-with-jest). +Возвращает объект, представляющий собой отрендеренное дерево. В дереве будут присутствовать только те ноды, которые специфичны +для платформы (например, ноды `
` или ``) и их пропсы. А вот компонентов, созданных пользователями, в этом дереве не будет. Это очень удобно для тестирования с помощью снимков. + ### `testRenderer.toTree()` {#testrenderertotree} @@ -118,7 +121,8 @@ Return an object representing the rendered tree. This tree only contains the pla testRenderer.toTree() ``` -Return an object representing the rendered tree. Unlike `toJSON()`, the representation is more detailed than the one provided by `toJSON()`, and includes the user-written components. You probably don't need this method unless you're writing your own assertion library on top of the test renderer. +Возвращает объект, представляющий собой отрендеренное дерево. В отличии от `toJSON()` в отрендеренное дерево попадут и самописные компоненты. Скорее всего, этот метод вряд ли будет полезен, пока вы не захотите создать поверх `TestRenderer` собственную бибилотеку тестирования. + ### `testRenderer.update()` {#testrendererupdate} @@ -126,7 +130,8 @@ Return an object representing the rendered tree. Unlike `toJSON()`, the represen testRenderer.update(element) ``` -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. +Повторный рендер находящегося в памяти дерева компонентов с учётом нового корневого элемента. По сути, это симуляция вызова React-обновления для корневого элемента. Если новый элемент имеет тот же тип и ключ, что и предыдущий, то дерево будет обновлено. Иначе, будет перемонтированно новое дерево. + ### `testRenderer.unmount()` {#testrendererunmount} @@ -134,7 +139,7 @@ Re-render the in-memory tree with a new root element. This simulates a React upd testRenderer.unmount() ``` -Unmount the in-memory tree, triggering the appropriate lifecycle events. +Отмонтировать дерево находящееся в памяти. При этом запустятся необходимые события жизненного цикла. ### `testRenderer.getInstance()` {#testrenderergetinstance} @@ -142,7 +147,8 @@ Unmount the in-memory tree, triggering the appropriate lifecycle events. testRenderer.getInstance() ``` -Return the instance corresponding to the root element, if available. This will not work if the root element is a function component because they don't have instances. +Получить, если возможно, экземпляр соответствующий верхнему элементу. Этот метод не сработает, если верхним элементом будет функциональный компонент, т.к. они не имеют экземляров (в отличии от классовых компонентов). + ### `testRenderer.root` {#testrendererroot} @@ -150,7 +156,7 @@ Return the instance corresponding to the root element, if available. This will n testRenderer.root ``` -Returns the root "test instance" object that is useful for making assertions about specific nodes in the tree. You can use it to find other "test instances" deeper below. +Получить доступ к тестовому экземпляру. Удобно использовать для тестирования конкретных нод в дереве. Полученный тестовый экземпляр можно также использовать и для поиска других тестовых экземпляров дальше вглубь по дереву. ### `testInstance.find()` {#testinstancefind} @@ -158,7 +164,8 @@ Returns the root "test instance" object that is useful for making assertions abo testInstance.find(test) ``` -Find a single descendant test instance for which `test(testInstance)` returns `true`. If `test(testInstance)` does not return `true` for exactly one test instance, it will throw an error. +Поиск единственного вложенного тестового экземпляра для которого `test(testInstance)` вернёт `true`. Метод `test(testInstance)` должен вернуть `true` ровно для одного тестового экземпляра, в противном случае вернётся ошибка. + ### `testInstance.findByType()` {#testinstancefindbytype} @@ -166,7 +173,8 @@ Find a single descendant test instance for which `test(testInstance)` returns `t testInstance.findByType(type) ``` -Find a single descendant test instance with the provided `type`. If there is not exactly one test instance with the provided `type`, it will throw an error. +Находит один вложенный тестовый экземпляр с указанным `type`. Метод `findByType` вернёт ошибку, если тестовых экземпляров с указанным `type` не найдено или найдено больше одного. + ### `testInstance.findByProps()` {#testinstancefindbyprops} @@ -174,7 +182,8 @@ Find a single descendant test instance with the provided `type`. If there is not testInstance.findByProps(props) ``` -Find a single descendant test instance with the provided `props`. If there is not exactly one test instance with the provided `props`, it will throw an error. +Находит один вложенный тестовый экземлпяр с указанными `props`. Метод `findByProps` вернёт ошибку, если тестовых экземпляров с указанными пропсами не найдено или найдено больше одного. + ### `testInstance.findAll()` {#testinstancefindall} @@ -182,7 +191,8 @@ Find a single descendant test instance with the provided `props`. If there is no testInstance.findAll(test) ``` -Find all descendant test instances for which `test(testInstance)` returns `true`. +Находит все вложенные тестовые инстансы для которых `test(testInstance)` возвращает `true`. + ### `testInstance.findAllByType()` {#testinstancefindallbytype} @@ -190,7 +200,7 @@ Find all descendant test instances for which `test(testInstance)` returns `true` testInstance.findAllByType(type) ``` -Find all descendant test instances with the provided `type`. +Находит все вложенные тестовые экземпляры с указанным `type`. ### `testInstance.findAllByProps()` {#testinstancefindallbyprops} @@ -198,7 +208,8 @@ Find all descendant test instances with the provided `type`. testInstance.findAllByProps(props) ``` -Find all descendant test instances with the provided `props`. +Найти все вложенные тестовые экземпляры c указанными пропсами. + ### `testInstance.instance` {#testinstanceinstance} @@ -206,7 +217,8 @@ Find all descendant test instances with the provided `props`. testInstance.instance ``` -The component instance corresponding to this test instance. It is only available for class components, as function components don't have instances. It matches the `this` value inside the given component. +Экземпляр компонента, соответствующий его тестовому экземпляру. Свойство доступно только для классовых компонентов, т.к. функциональные компоненты не имеют экземпляров. Этот экземпляр компонента будет соответствовать значению this внутри данного компонента. + ### `testInstance.type` {#testinstancetype} @@ -214,7 +226,8 @@ The component instance corresponding to this test instance. It is only available testInstance.type ``` -The component type corresponding to this test instance. For example, a `