Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在jest测试中模拟json.parse()_Json_Reactjs_Parsing_Jestjs - Fatal编程技术网

如何在jest测试中模拟json.parse()

如何在jest测试中模拟json.parse(),json,reactjs,parsing,jestjs,Json,Reactjs,Parsing,Jestjs,我的代码中有一个try/catch,当代码落入catch部分时,它会命中一个JSON.parse() 代码正在运行,但测试失败。测试只是断言try中发生了什么 try { popUp.method(mockedUrl) } 测试只是断言调用了此方法,但它失败了,因为JSON.parse()阶段出现了问题。我只是想知道如何将它剔除,以便它知道我传递给json的是什么?您可以模拟json.parse实现 JSON.parse = jest.fn().mockImplementationOnc

我的代码中有一个try/catch,当代码落入
catch
部分时,它会命中一个JSON.parse()

代码正在运行,但测试失败。测试只是断言try中发生了什么

try {
   popUp.method(mockedUrl)
}

测试只是断言调用了此方法,但它失败了,因为
JSON.parse()阶段出现了问题。我只是想知道如何将它剔除,以便它知道我传递给json的是什么?

您可以模拟json.parse实现

JSON.parse = jest.fn().mockImplementationOnce(() => {
  // return your what your code is returning.
});

一旦您不应该测试javascript内置对象:JSON,这就足够了。因此,您可以返回代码所期望的结果,其余的都可以。

您可以参考它。这很可能是个问题。通常,您需要模拟传递给JSON.parse的数据,而不是JSON.parse本身。@estus ok true。但是当我在catch块中注销
err
时,它甚至没有显示任何内容。当我
console.log('hello')
显示时。这让我很困惑。我猜它不知道什么是错误is@Xanax那是在用西农,不是杰斯蒂,我不知道你的案子是什么。您想模拟它以进行测试还是调试?您在何处记录错误以及哪些错误可以不显示?它到底是一个物体吗?
JSON.parse(err.message)
?它什么也没做。请发布您正在测试的代码和测试,这样您的案例就更清楚了。您可以将JSON.parse模拟为任何其他方法,但这可能是错误的决定。
JSON.parse = jest.fn().mockImplementationOnce(() => {
  // return your what your code is returning.
});