如何使jest mock可重用?

qzlgjiam  于 2023-09-28  发布在  Jest
关注(0)|答案(1)|浏览(187)

我有下面这个嘲笑react-i18 next的笑话。

  1. jest.mock('react-i18next', () => ({
  2. useTranslation: () => {
  3. return {
  4. t: (str: string, { ns, defaultValue }) => defaultValue,
  5. i18n: {
  6. changeLanguage: () => new Promise(() => {}),
  7. },
  8. };
  9. },
  10. initReactI18next: {
  11. type: '3rdParty',
  12. init: () => {},
  13. },
  14. }));

我试图通过创建一个新的文件来使它可重用,如下所示。但是导入和运行MyReusableMockFunction并不会模拟spec文件中的react-i18 next。这里会出什么问题呢有什么方法可以使这个mock可重用

  1. import {jest} from '@jest/globals'
  2. export const MyReusableMockFunction=()=>{
  3. jest.mock('react-i18next', () => ({
  4. useTranslation: () => {
  5. return {
  6. t: (str: string, { ns, defaultValue }) => defaultValue,
  7. i18n: {
  8. changeLanguage: () => new Promise(() => {}),
  9. },
  10. };
  11. },
  12. initReactI18next: {
  13. type: '3rdParty',
  14. init: () => {},
  15. },
  16. }));
  17. }
mm5n2pyu

mm5n2pyu1#

我假设你想在全局上模拟i18 n。最简单的方法是将其添加到jest.setup.js文件中。然后在所有测试中模拟它(我们使用i18 next而不是react-i18 next,所以实际的模拟可能会有所不同):

  1. jest.doMock('i18next', () => ({
  2. use: () => ({
  3. init: jest.fn(),
  4. }),
  5. changeLanguage: () => {
  6. return Promise.resolve();
  7. },
  8. /**
  9. * Mocks the t function of i18next
  10. * If you pass parameters to the t function they will be stringified and added to the key.
  11. */
  12. t: (key, parameters) => (parameters ? key + JSON.stringify(parameters) : key),
  13. }));

如果出于某种原因不想在testFile中使用它,可以取消模拟:

  1. jest.unmock('i18next');

这里也是一个关于使用mock doMock unmock和dontMock进行提升的有趣答案:Difference between jest.mock and jest.doMock

展开查看全部

相关问题