简体   繁体   English

Mocking 笑话网络 - 我如何不干燥我的格式化程序?

[英]Mocking jest network - how do I not DRY my formatter?

I have a network module to ping a legacy database with data in multiple formats, and I want to standardize it here in the network module before passing it into the application so my application can expect a certain format of data (don't want the old, poor formatting polluting my business logic).我有一个网络模块来 ping 具有多种格式数据的遗留数据库,我想在将它传递到应用程序之前在网络模块中对其进行标准化,以便我的应用程序可以期待某种格式的数据(不想要旧的,糟糕的格式污染了我的业务逻辑)。 I'm struggling with how to pass mock data through as this network module, specifically as it relates to the formatter.我正在努力解决如何作为这个网络模块传递模拟数据,特别是因为它与格式化程序有关。 Here's what I mean:这就是我的意思:

// User API Network Module
// UserAPI.ts
export const getUser = (uid: String, callback: (GetUserResponse) => void): void => {
  // Do network call here and format the data into a typescript type
  // matching the GetUserResponse structure by business logic expects
  callback(formattedData)
}

In my test file, I can mock this call easily with:在我的测试文件中,我可以轻松地模拟这个调用:

import { getUser } from "./UserAPI"
jest.mock("./UserAPI", () => ({
  getUser: (uid: String, callback: (GetUserResponse) => void) => {
    const mockedUserData = require("./mockUser.json")
    // But how do I format it here?
    return formattedMockedUserData
  },
}))

I can create a formatter function in my UserAPI.ts file, export it, and run it in the jest mock, but I'm wondering if that's a best practice because it technically leaks the UserAPI implementation details.我可以在我的UserAPI.ts文件中创建一个格式化程序 function ,将其导出,然后在开玩笑的模拟中运行它,但我想知道这是否是最佳实践,因为它在技术上泄露了UserAPI实现细节。 And I point that out only because no other file cares about how UserAPI formats things except UserAPI .我指出这一点只是因为没有其他文件关心UserAPI如何格式化除UserAPI之外的东西。 If I have to leak it for testing purposes, I'll do that.如果我必须出于测试目的泄漏它,我会这样做。 But is there a better way to mock the network call and run it through a formatter without exposing additional implementation details?但是有没有更好的方法来模拟网络调用并通过格式化程序运行它而不暴露额外的实现细节?

And please be gentle on my typescript - I come from both a JS and strongly typed background, but this is my first venture into using typescript:)请对我的 typescript 温柔一点——我来自 JS 和强类型背景,但这是我第一次尝试使用 typescript :)

Even though it's not used multiple places extract it - following Single Responsibility Principle - into its own construct.即使它没有在多个地方使用,也可以按照单一责任原则将其提取到自己的结构中。 You test all formatting logic in Formmater Test not in User API Test.您在 Formmater 测试中测试所有格式化逻辑,而不是在用户 API 测试中测试。 Additionally you can test the integration of Formatter with User API in an Integration Test.此外,您可以在集成测试中测试 Formatter 与用户 API 的集成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM