grPC的jest模拟失败了手动定义

时间:2017-04-23 02:45:13

标签: javascript reactjs unit-testing jestjs grpc

我试图测试React组件,组件的存储正在进行一些gRPC通信,因此需要grpc node_module。我的测试是通过链接导入grpc,因为它导入了React组件,后者导入了导入grpc的商店。

这很好,但是automock失败了: 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

所以我在每个Jest Documentation的node_modules旁边放置一个 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,似乎都没有帮助。

任何想法/建议/解决方法?

1 个答案:

答案 0 :(得分:1)

不幸的是,通过使用export default grps,您的模块实际上导出了es模块:

{
   default: {
       makeGenericClientConstructor: ...
   }
}

如果您访问grpc.default.makeGenericClientConstructor,那么您可以确认这是真的。

如果您告诉Jest将ES模块模拟编译到CommonJS(通过babel),在您的环境中使用ES模块可以正常工作,但如果您不这样做,那么您只想导出您的模块使用以下命令模拟为CommonJS模块:

module.exports = grpc;
相关问题