如何使用Shallow组件Jest / Enzyme针对不同的测试场景提供不同的模拟实现?

时间:2020-06-23 11:44:17

标签: javascript reactjs typescript jestjs enzyme

我创建了一个嘲笑Api,它将首先在__mocks__文件夹中返回值“ hasStores:true”,并使用useEffect钩子调用嘲笑Api。

useEffect(() => {
    getNotifications().then((result) => setNotifications(result))
}

我正在做的第一个测试基于useEffect返回hasStores:true做一个浅表,它成功地工作了。然后,我尝试通过进行模拟并更改实现以返回“ hasStores:false”来创建另一个测试。

const mockApi = require('../../../api/myApi')
jest.spyOn(mockApi, 'getNotifications').mockImplementation(() => {return({hasStores: false })})

然后这将更新hasStores的状态以返回false,但是在执行浅表操作时崩溃。 'TypeError:(0,_dashboardApi.getNotifications)(...)。然后不是函数'

const dashboardWarning = shallow(<Dashboard />)

1 个答案:

答案 0 :(得分:0)

我认为您没有正确嘲笑 getNotifications 功能。您正在提供同步实现, .then()不能紧跟其后。请尝试:

for (int x = 1; x<9; x++)
{
 y = x*x;
 Console.WriteLine(x, y)
}

甚至更好

jest.spyOn(mockApi, 'getNotifications').mockImplementation(() => Promise.resolve({hasStores: false }))