简体   繁体   English

Mocking 带有 Jest 的 class 返回另一个 class

[英]Mocking a class with Jest which returns another class

I come from a C# NUnit background so I am struggling to make sense of how to mock imports using Jest in TypeScript.我来自 C# NUnit 背景,所以我很难理解如何在 TypeScript 中使用 Jest 模拟导入。

In my method that I want to test, I've got a call to a module which then returns a class.在我想测试的方法中,我调用了一个模块,然后返回一个 class。 This then goes on and calls a couple other functions before returning the list that I want.然后继续并在返回我想要的列表之前调用其他几个函数。

import { Metaplex, Nft } from "@metaplex-foundation/js-next"

async doSomething(walletAddress: string): Promise<MyType>
{
  const metaplex = Metaplex.make(QuickNodeService.connection)
  const data = await metaplex
    .nfts()
    .findAllByOwner(new PublicKey(walletAddress))
  // carry on doing stuff with the data
}

I have been ripping my hair out trying to figure out how to mock Metaplex and add some well needed unit tests in. I just want to verify that findAllByOwner is called with the correct walletAddress and to mock the return so I can verify what I do with data is correct.我一直在试图弄清楚如何模拟 Metaplex 并添加一些非常需要的单元测试。我只想验证findAllByOwner是否使用正确的walletAddress并模拟返回,以便我可以验证我做了什么data正确。

Can anyone help me or point me in the right direction?任何人都可以帮助我或指出我正确的方向吗? Thanks in advance!提前致谢!

Don't mock what you don't own.不要嘲笑你不拥有的东西。

Make an adapter (a wrapper) and mock that.制作一个适配器(一个包装器)并模拟它。

Bonus: When you decide to switch to a different dependency in the future, you'll have one chokepoint to modify and test while all the rest of your source code can remain unchanged.奖励:您决定将来切换到不同的依赖项时,您将有一个阻塞点需要修改和测试,而您的源代码的所有 rest 可以保持不变。

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

相关问题 用jest模拟打字稿中的类 - Mocking a class in typescript with jest 开玩笑模拟多个类实例 - Jest Mocking Multiple Class instances 使用 TypeScript 在 Jest 中模拟 ES6 类方法 - Mocking ES6 class method in Jest with TypeScript Mocking 默认导出方法 class 在 Typescript - Mocking method on default export class in Jest in Typescript 在打字稿测试中用玩笑模拟从另一个文件调用的函数 - Mocking a function which is called from another file in typescript tests with jest 为什么jest v24模拟类需要私有方法 - why is jest v24 mocking class requiring private methods 开玩笑的 TypeScript 类“没有重载需要 1 个类型参数” - Jest mocking TypeScript class "No overload expects 1 type arguments" 打字稿,在 Redux 动作中测试 Api 调用,在 Enzyme 中模拟类,Jest - Typescript,testing Api calls in Redux actions, mocking class in Enzyme, Jest 当 mocking 使用 Typescript 在 Jest 中使用 class 时引发“缺少分号”错误 - “Missing semicolon” error raised when mocking a class in Jest using Typescript Mocking 来自一个模块的单个 function 也从另一个模块调用它 function,开玩笑,typescript - Mocking single function from a module which also calls it from another function, jest, typescript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM