在测试之间开玩笑地更改 POJO 模块的模拟实现

木乃伊机器人

我试图在测试中模拟普通旧 Javascript 对象的导入,我希望每个测试都有不同的实现。

如果我在文件顶部模拟它按预期工作:

import { getConfig } from './'; // this contains the import config from 'configAlias';

jest.mock('configAlias', () => ({
  hello: 'world',
}));

it('passes test', () => {
  expect(getConfig()).toEqual({
    hello: 'world,
  });
});

但是我找不到任何 doMock 组合,默认命名导出,mockImplementation 来使以下内容起作用:

import { getConfig } from './'; // this contains the import config from 'configAlias';


it('fails test1', () => {
  jest.doMock('configAlias', () => ({
    hello: 'world',
  }));
  const config = require('configAlias');

  expect(getConfig()).toEqual({
    hello: 'world,
  });
});

it('fails test2', () => {
  jest.doMock('configAlias', () => ({
    hello: 'moon',
  }));
  const config = require('configAlias');

  expect(getConfig()).toEqual({
    hello: 'moon,
  });
});

编辑 1

基于@jonrsharpe,我尝试过

import { getConfig } from './'; // this contains the import config from 'configAlias';

const mockConfig = jest.fn();
jest.mock('configAlias', () => mockConfig);

it('fails test', () => {
  mockConfig.mockImplementation({
    hello: 'world',
  });
  expect(getSchema()).toEqual({ hello: 'world' });
});
木乃伊机器人

解决了这个问题,诀窍是在单个测试中设置模拟后导入/要求被测文件(不是模拟文件)。文件顶部没有导入。

beforeEach(() => {
  jest.resetModules();
});

it('passes test 1', () => {
  jest.mock('configAlias', () => ({
    hello: 'world',
  }));
  const { getConfig } = require('getConfig');

  expect(getConfig()).toEqual({
    hello: 'world',
  });
});

it('passes test 2', () => {
  jest.mock('configAlias', () => ({
    hello: 'moon',
  }));
  const { getConfig } = require('getConfig');

  expect(getConfig()).toEqual({
    hello: 'moon',
  });
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

开玩笑地测试模块功能

如何在类中开玩笑地模拟节点模块?

开玩笑地模拟静态吸气剂

开玩笑地测试上下文/监视在函数外部创建的模拟变量(类级别)

您可以开玩笑地只模拟外部模块的一部分吗?

我如何开玩笑地模拟 firebase analitycs?

如何开玩笑地模拟一个咖喱函数?

用 Typescript 开玩笑地模拟一个库

如何开玩笑地模拟多个 axios 调用?

开玩笑 - 更改模拟实现不起作用

如何开玩笑地测试

如何在Jest的模拟模块中更改函数的模拟实现

开玩笑:在手动模拟中恢复原始模块的实现

如何模拟接收到的回调函数的数据(参数),以便可以开玩笑地测试回调函数中的逻辑?(例如fs.readFile)

开玩笑的单次导入模拟模块

开玩笑地测试discord bot命令

如何在 redux 中开玩笑地模拟异步动作创建者

开玩笑地模拟一个日期,在不同的环境中无法正常工作

在函数内模拟函数并开玩笑地获取调用计数

开玩笑地模拟一个toPromise函数.toPromise不是一个函数

开玩笑地确认快照更改

开玩笑+超级测试:如何重置模拟的依赖项

如何模拟css导入进行开玩笑/酶测试?

开玩笑:模拟console.error-测试失败

开玩笑:监视正在测试的模块中的其他功能

模拟仅用于开玩笑地在浏览器中运行的 fetch 调用的最简单方法是什么?

无法使用打字稿开玩笑地模拟fs-类型上不存在属性'mockReturnValue'

开玩笑:模拟第三方模块

TypeScript无法识别我开玩笑的模拟模块