在多个测试中共享 jest 模拟模块的单个实现

时间:2021-05-14 04:57:39

标签: reactjs typescript unit-testing jestjs

上下文

我想在多个测试中共享一个模拟模块,而不必一直复制和粘贴自定义实现。

我们使用 Console.Write("Enter a string to encode: "); string input = Console.ReadLine(); Random r = new Random(); char[] characters = " ~!@#$%^&*()_+=-0987654321`{}|\\][\"';:/?.>,<QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm".ToCharArray(); string method = ""; bool f = true; var unused = characters.ToList(); while (method.Length != characters.Length) { char cc = unused[r.Next(0, unused.Count)]; method = method + cc; unused.Remove(cc); } 库来处理我们的翻译,随之而来的是一个名为 next-i18next 的钩子,它返回 useTranslations() 函数。通常它被调用如下:

t

在测试 // SomeComponent.tsx export const SomeComponent: FunctionComponent = () => { ... const { t } = useTranslation('common') ... } 时,设置通常如下所示,在导入下方的文件顶部使用 SomeComponent.tsx 模拟 useTranslations() 钩子。

jest.mock(...)

这很有效,除了我必须在使用 // SomeComponent.test.tsx // imports jest.mock('next-i18next', () => ({ useTranslation: () => ({ t: (e) => e }) })) describe('SomeComponent tests', () => { test('should do something', () => { ... }) }) 钩子的每个测试中复制和粘贴 jest.mock(...) 部分。我们有很多组件,其中很多都使用 useTranslation()

实际问题

我已尝试使用 useTranslation 文件夹方法遵循此处列出的指南:https://jestjs.io/docs/manual-mocks

我的目录结构已设置为如下所示:

__mocks__

然后我在 ... ├── node_modules ├── __mocks__ │ └── next-i18next.ts ├── src └──SomeComponent ├── SomeComponent.test.tsx └── SomeComponent.tsx ├── other.ts ... 文件的顶部添加了一个简单的 jest.mock,使其看起来像这样

SomeComponent.test.tsx

但它并没有真正起作用,我似乎总是遇到以下错误:

// SomeComponent.test.tsx

// imports

jest.mock('next-i18next')

describe('SomeComponent tests', () => {
  
  test('should do something', () => {
    ...
  })
})

对如何做到这一点有任何想法吗?

编辑

对于模拟,我基本上尝试使用 TypeError: (0 , _nextI18next.useTranslation) is not a function

执行他们在文档中演示的操作
fs

0 个答案:

没有答案