如何让 .toThrow 响应抛出

How to make .toThrow react to throw

Jest .toThrow 不响应抛出错误('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;
};

您必须将调用包装到抛出的函数,否则会出现错误 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();
});