Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Отключить injectGlobals в Jest #358

Open
krutoo opened this issue Oct 6, 2023 · 3 comments
Open

Отключить injectGlobals в Jest #358

krutoo opened this issue Oct 6, 2023 · 3 comments
Assignees

Comments

@krutoo
Copy link
Member

krutoo commented Oct 6, 2023

Ситуация

Сейчас в тесты инжектятся глобальные переменные Jest

у этого есть ряд минусов

например они также подсказываются в НЕ тестах

лучше импортировать явно

Необходимо

задать опцию injectGlobals: false в конфиге Jest

пройтись по тестам и с помощью примерно такого скрипта докинуть импорты:

import fs from 'node:fs/promises';
import glob from 'fast-glob';

/** */
async function prependFile(path, line) {
  const data = await fs.readFile(path);
  const handle = await fs.open(path, 'w+');
  const insert = Buffer.from(line);

  await handle.write(insert, 0, insert.length, 0);
  await handle.write(data, 0, data.length, insert.length);
  await handle.close();
}

const imports = `import { describe, test, expect, jest } from '@jest/globals';\n`;

glob('./src/**/*.test.*').then(items => Promise.all(items.map(path => prependFile(path, imports))));
@krutoo krutoo self-assigned this Oct 6, 2023
@krutoo
Copy link
Member Author

krutoo commented Oct 6, 2023

что-то не так
testing-library/react-testing-library#1240

UPD: помогли

@krutoo
Copy link
Member Author

krutoo commented Oct 18, 2023

еще есть вот такая сложность
testing-library/user-event#1173

krutoo added a commit that referenced this issue Oct 19, 2023
- мелкие todo (patch)
- мелкие правки типов (удалено использование глобального неймспейса React) (patch)
- layout: теперь не используются css-переменные (patch)
krutoo added a commit that referenced this issue Oct 19, 2023
- правки снепшотов
krutoo added a commit that referenced this issue Oct 19, 2023
#358

- мелкие todo (patch)
- мелкие правки типов (удалено использование глобального неймспейса React) (patch)
- layout: теперь не используются css-переменные (patch)
krutoo added a commit that referenced this issue Oct 19, 2023
- отказ от использования глобального неймспейса React (patch)
krutoo added a commit that referenced this issue Oct 20, 2023
- pagination: правки обработки пропа getItems (patch)
- input: в сторибук добавлен пример без label и placeholder
krutoo added a commit that referenced this issue Oct 20, 2023
- pagination: правки обработки пропа getItems (patch)
- input: в сторибук добавлен пример без label и placeholder
@krutoo
Copy link
Member Author

krutoo commented Jan 23, 2024

скрипт для правки тестов:

import fs from 'node:fs/promises';
import glob from 'fast-glob';

/**
 * Добавляет контент в начало файла.
 * @param {string} filename Путь до файла.
 * @param {string} content Контент для добавления в начало.
 */
async function prependFile(filename, content) {
  const data = await fs.readFile(filename);
  const handle = await fs.open(filename, 'w+');
  const insert = Buffer.from(content);

  await handle.write(insert, 0, insert.length, 0);
  await handle.write(data, 0, data.length, insert.length);
  await handle.close();
}

glob('src/**/*.test.{ts,tsx}').then(list =>
  Promise.all(
    list.map(filename =>
      fs.readFile(filename, 'utf-8').then(source => {
        const imports = ['it', 'expect', 'describe'];

        source.includes('beforeAll') && imports.push('beforeAll');
        source.includes('afterAll') && imports.push('afterAll');
        source.includes('beforeEach') && imports.push('beforeEach');
        source.includes('afterEach') && imports.push('afterEach');
        source.includes('jest') && imports.push('jest');

        return prependFile(filename, `import { ${imports.join(', ')} } from '@jest/globals';\n`);
      }),
    ),
  ),
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant