【问题标题】:How to make .toThrow react to throw如何使 .toThrow 对投掷做出反应
【发布时间】:2019-03-31 17:05:24
【问题描述】:

Jest .toThrow 不响应 throw Error('some text')

这段代码产生异常

if (!['diff', 'plain', 'json'].includes(format.toLowerCase())) {
    throw Error('Wrong format');
  }

我正在尝试在测试中处理它

test('tree, yml, plan, Exception_', () => {
  const fileName1 = '__tests__/__fixtures__/before.json';
  const fileName2 = '__tests__/__fixtures__/after.jso';
  expect(genDiff(fileName1, fileName2)).toThrow();
});

但是这个测试失败了

很奇怪,因为这是正确处理的:

test('t', () => {
  expect(() => {
    throw Error();
  }).toThrow();
});

如何解决这个问题?

这里是函数

const genDiff = (fileName1, fileName2, format = 'diff') => {
  const wrongFiles = checkForWrongFiles([fileName1, fileName2]);
  if (wrongFiles.length !== 0) {
    const errorMessage = `Could not find this files:\n ${wrongFiles.join('\n')}`;
    throw errorMessage;
  }
  if (!['diff', 'plain', 'json'].includes(format.toLowerCase())) {
    throw Error('Wrong format');
  }
  ...
  return result;
};

【问题讨论】:

  • 你的genDiff函数在哪里?
  • 嗨,请添加文件的内容以及我们整个genDiff。我们无法猜测这个函数的内容和format的上下文。
  • genDiff - 主函数,在 index.js 中
  • @АндрейДенисов 将此功能添加到问题中。
  • Omri,格式和文件的内容完全没有问题,因为在任何处理之前抛出异常。我可以把它放在函数 genDiff 的第一个字符串上,我会用眼睛开玩笑地看到异常,但是测试失败了。

标签: javascript jestjs throw


【解决方案1】:

您必须包装对抛出函数的调用,否则会出现错误is not catched by the assertions(请参阅底部的注释)。请注意,我已将对 genDiff 的调用封装在一个函数中。

test('tree, yml, plan, Exception_', () => {
  const fileName1 = '__tests__/__fixtures__/before.json';
  const fileName2 = '__tests__/__fixtures__/after.jso';
  expect(() => genDiff(fileName1, fileName2)).toThrow();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-18
    • 2014-04-27
    • 2021-05-12
    • 2023-03-16
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    • 2017-11-08
    相关资源
    最近更新 更多