gRPC 的开玩笑模拟因手动定义而失败
Jest mock of gRPC fails with manual definition
我正在尝试测试一个 React 组件,该组件的存储正在进行一些 gRPC 通信,因此需要 grpc node_module。我的测试是通过链接导入 grpc,因为它导入 React 组件,React 组件导入商店,商店导入 grpc。
很好,但是自动模拟失败了:
Error: The specified module could not be found. \?\C:\Dev\Projects\Electron\PAT\client\app\node_modules\grpc\src\node\extension_binary\grpc_node.node
所以我在 node_modules per Jest Documentation 旁边放置了一个 mocks 文件夹,并在其中创建了 grpc.js:
const grpc = {};
export default grpc;
这让我更进一步,但是:
TypeError: grpc.makeGenericClientConstructor is not a function
可以理解,所以我尝试将grpc.js改为:
const grpc = { makeGenericClientConstructor: () => { return; } };
但我继续得到同样的错误:
TypeError: grpc.makeGenericClientConstructor is not a function
我试过使用 jest.setMock 和 jest.mock,但似乎都没有用。
任何ideas/suggestions/workarounds?
不幸的是,通过使用 export default grps
,您的模块实际上导出了一个 es 模块:
{
default: {
makeGenericClientConstructor: ...
}
}
如果您访问 grpc.default.makeGenericClientConstructor
并且它就在那里,您可以确认这是真的。
如果您告诉 Jest 将 ES 模块模拟编译为 CommonJS(通过 babel),那么在您的环境中使用 ES 模块就可以正常工作,但如果您不这样做,那么您将只想将模拟导出为CommonJS 模块使用:
module.exports = grpc;
我正在尝试测试一个 React 组件,该组件的存储正在进行一些 gRPC 通信,因此需要 grpc node_module。我的测试是通过链接导入 grpc,因为它导入 React 组件,React 组件导入商店,商店导入 grpc。
很好,但是自动模拟失败了:
Error: The specified module could not be found. \?\C:\Dev\Projects\Electron\PAT\client\app\node_modules\grpc\src\node\extension_binary\grpc_node.node
所以我在 node_modules per Jest Documentation 旁边放置了一个 mocks 文件夹,并在其中创建了 grpc.js:
const grpc = {};
export default grpc;
这让我更进一步,但是:
TypeError: grpc.makeGenericClientConstructor is not a function
可以理解,所以我尝试将grpc.js改为:
const grpc = { makeGenericClientConstructor: () => { return; } };
但我继续得到同样的错误:
TypeError: grpc.makeGenericClientConstructor is not a function
我试过使用 jest.setMock 和 jest.mock,但似乎都没有用。
任何ideas/suggestions/workarounds?
不幸的是,通过使用 export default grps
,您的模块实际上导出了一个 es 模块:
{
default: {
makeGenericClientConstructor: ...
}
}
如果您访问 grpc.default.makeGenericClientConstructor
并且它就在那里,您可以确认这是真的。
如果您告诉 Jest 将 ES 模块模拟编译为 CommonJS(通过 babel),那么在您的环境中使用 ES 模块就可以正常工作,但如果您不这样做,那么您将只想将模拟导出为CommonJS 模块使用:
module.exports = grpc;