【问题标题】:Jest mock of gRPC fails with manual definitiongRPC 的玩笑模拟因手动定义而失败
【发布时间】:2017-04-23 02:45:13
【问题描述】:

我正在尝试测试一个 React 组件,该组件的存储正在进行一些 gRPC 通信,因此需要 grpc node_module。我的测试是通过链式导入 grpc,因为它导入了 React 组件,该组件导入了 store,该组件导入了 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,但似乎都没有帮助。

有什么想法/建议/解决方法吗?

【问题讨论】:

  • 开玩笑将其评估为 ES6 模块吗?如果您使用 commonjs 而不是使用export default grpc;,会发生什么? module.exports = grpc;?
  • 这已解决,谢谢!你想回答这个问题吗?

标签: javascript reactjs unit-testing jestjs grpc


【解决方案1】:

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

{
   default: {
       makeGenericClientConstructor: ...
   }
}

如果您访问grpc.default.makeGenericClientConstructor 并且它就在那里,您可以确认这是真的。

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

module.exports = grpc;

【讨论】:

    猜你喜欢
    • 2019-02-15
    • 1970-01-01
    • 2017-11-19
    • 2018-04-29
    • 2019-01-30
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 2021-09-10
    相关资源
    最近更新 更多