如何让.toThrow做出反应

问题描述 投票:0回答:1

Jest .toThrow没有反应抛出错误('一些文字')

此代码产生异常

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;
};
javascript jestjs throw
1个回答
0
投票

你必须将调用包装到抛出的函数,否则错误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();
});
© www.soinside.com 2019 - 2024. All rights reserved.