Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ NextjsPanda copy/.next
ViteEmotion/node_modules
ViteAxiosZod/node_modules
ViteOnlineStore/node_modules
UnitTest/node_modules
YandexOuth
Optimization


/.pnp
.pnp.js
Expand Down
25 changes: 25 additions & 0 deletions UnitTest/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
coverage
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
67 changes: 67 additions & 0 deletions UnitTest/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Описание проекта

Вы разрабатываете приложение для управления списком задач (**Todo App**).

## Функционал:

- Добавление новой задачи
- Отметка задачи как выполненной
- Удаление задачи
- Фильтрация задач (все, активные, выполненные)

# Задание

## 1. Юнит-тесты (Jest + React Testing Library)

Напишите тесты для следующих компонентов:

### 1.1. Компонент `TodoItem`

- Проверьте, что задача отображается корректно (текст, статус выполнения)
- Проверьте, что кнопка удаления вызывает соответствующий обработчик
- Проверьте, что переключение статуса (выполнено/не выполнено) работает

### 1.2. Компонент `AddTodo`

- Проверьте, что ввод текста и отправка формы вызывают добавление задачи
- Проверьте, что форма очищается после отправки

## 2. Интеграционные тесты (Jest + RTL + MSW)

Проверьте взаимодействие компонентов и работу с API:

### 2.1. Интеграция `TodoList` и `TodoItem`

- Проверьте, что список задач корректно отображает переданные задачи
- Проверьте, что изменение статуса задачи в `TodoItem` обновляет состояние в `TodoList`

### 2.2. Работа с API (Mock Service Worker)

Замокайте API (например, fetch или axios) с помощью MSW.

Проверьте, что:

- При загрузке страницы задачи подгружаются с API
- Добавление новой задачи отправляет запрос к API

## 3. E2E-тесты (Cypress или Playwright)

Напишите сквозные тесты для ключевых сценариев:

### 3.1. Добавление задачи

1. Пользователь открывает приложение
2. Вводит текст задачи и нажимает "Добавить"
3. Проверяет, что задача появилась в списке

### 3.2. Удаление задачи

1. Пользователь добавляет задачу
2. Нажимает кнопку удаления
3. Проверяет, что задача исчезла из списка

### 3.3. Фильтрация задач

1. Пользователь добавляет несколько задач (активные и выполненные)
2. Переключает фильтр "Только активные" — проверяет, что видны только активные задачи
3. Переключает фильтр "Только выполненные" — проверяет, что видны только выполненные задачи.
9 changes: 9 additions & 0 deletions UnitTest/babel.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"presets": [
"@babel/preset-env",
["@babel/preset-react", {
"runtime": "automatic"
}],
"@babel/preset-typescript"
]
}
18 changes: 18 additions & 0 deletions UnitTest/cypress.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { defineConfig } from 'cypress';

export default defineConfig({
e2e: {
baseUrl: 'http://localhost:5173',
supportFile: false,
setupNodeEvents(on, config) {
// implement node event listeners here
},
},

component: {
devServer: {
framework: 'react',
bundler: 'vite',
},
},
});
62 changes: 62 additions & 0 deletions UnitTest/cypress/e2e/e2e.cy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
describe('E2E Tests', () => {
it('Add Task', () => {
cy.visit('http://localhost:5173/');
cy.get('[data-testid="todo-input"]').type('Add Task');
cy.get('[data-testid="add-button"]').click();
cy.get('span').should('contain.text', 'Add Task');
});

it('Delete task', () => {
cy.visit('http://localhost:5173/');
cy.get('[data-testid="todo-input"]').type('Delete task');
cy.get('[data-testid="add-button"]').click();
cy.get('[data-testid="todo-input"]').should('have.attr', 'value', '');
});

it('Filter', () => {
cy.visit('http://localhost:5173/');

// Добавление активной задачи
cy.get('[data-testid="todo-input"]').type('Todo task x');
cy.get('[data-testid="add-button"]').click();

// Добавление выполненной задачи
cy.get('[data-testid="todo-input"]').type('Done task x');
cy.get('[data-testid="add-button"]').click();

// Ожидание появления последнего элемента перед кликом
cy.get('[data-testid^="toggle-"]').should('have.length.at.least', 4); // Убедиться, что есть хотя бы 2 задачи
cy.get('[data-testid^="toggle-"]').last().click();

// Добавление ещё одной активной задачи
cy.get('[data-testid="todo-input"]').type('Todo task y');
cy.get('[data-testid="add-button"]').click();

// Проверка фильтра "Только активные"
cy.get('[data-testid="filter-active"]').click();
cy.get('[data-testid="todo-list"]', { timeout: 10000 }).should(
'contain.text',
'Todo task x',
);
cy.get('[data-testid="todo-list"]').should('contain.text', 'Todo task y');
cy.get('[data-testid="todo-list"]').should(
'not.contain.text',
'Done task x',
);

// Проверка фильтра "Только выполненные"
cy.get('[data-testid="filter-completed"]').click();
cy.get('[data-testid="todo-list"]', { timeout: 10000 }).should(
'contain.text',
'Done task x',
);
cy.get('[data-testid="todo-list"]').should(
'not.contain.text',
'Todo task x',
);
cy.get('[data-testid="todo-list"]').should(
'not.contain.text',
'Todo task y',
);
});
});
5 changes: 5 additions & 0 deletions UnitTest/cypress/fixtures/example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "Using fixtures to represent data",
"email": "hello@cypress.io",
"body": "Fixtures are a great way to mock data for responses to routes"
}
25 changes: 25 additions & 0 deletions UnitTest/cypress/support/commands.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add('login', (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })
12 changes: 12 additions & 0 deletions UnitTest/cypress/support/component-index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Components App</title>
</head>
<body>
<div data-cy-root></div>
</body>
</html>
24 changes: 24 additions & 0 deletions UnitTest/cypress/support/component.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// ***********************************************************
// This example support/component.js is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************

// Import commands.js using ES2015 syntax:
import './commands'

import { mount } from 'cypress/react'

Cypress.Commands.add('mount', mount)

// Example use:
// cy.mount(<MyComponent />)
28 changes: 28 additions & 0 deletions UnitTest/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'

export default tseslint.config(
{ ignores: ['dist'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
},
)
13 changes: 13 additions & 0 deletions UnitTest/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
30 changes: 30 additions & 0 deletions UnitTest/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export default {
testEnvironment: 'jest-fixed-jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.cjs'],
transform: {
'^.+\\.(js|jsx|ts|tsx)$': 'babel-jest',
},
testPathIgnorePatterns: ['/node_modules/', '/cypress/'],
collectCoverageFrom: [
'src/components/*.js',
'src/mocks/*.js',
'src/components/*.ts',
'src/components/*.jsx',
'src/components/*.tsx',
'!src/index.js', // files you need to avoid in test coverage
'!src/hooks/*.js',
'!src/context/*.js',
],
coverageThreshold: {
global: {
branches: 90,
functions: 90,
lines: 90,
statements: 90,
},
},
coverageReporters: ['html', 'text'],
testEnvironmentOptions: {
customExportConditions: [''],
},
};
1 change: 1 addition & 0 deletions UnitTest/jest.setup.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
require('@testing-library/jest-dom');
Loading