typescript - 开玩笑:类模拟不使用 mockImplementation
问题描述
PropertyBasedCache.ts
export class PropertyBasedCache {
get(key: string) {
// return value from cache if any
}
set(key: string, value: any) {
// cache value
return this.get(key)
}
}
变压器.ts
export class Transformer {
private cache: PropertyBasedCache
constructor() {
this.cache = new PropertyBasedCache()
}
transform() {
if(this.cache.get("key")) {
return this.cache.get("key")
}
}
}
SomeTest.test.ts
import { PropertyBasedCache } from "./PropertyBasedCache"
import { Transformer } from "./Transformer.ts"
jest.mock("./PropertyBasedCache", () => ({
PropertyBasedCache: jest.fn().mockImplementation(() => ({
get: jest.fn(),
set: (_, value) => value
}))
}))
test("should use cached value on subsequent calls", () => {
const transformer = new Transformer()
// ↓ Throws `cache.get` is not a function
// `console.log(this.cache)` inside of `Transformer` logs `mockConstructor {}`
transformer.transform()
})
我遵循了关于模拟非默认类导出的官方文档:https ://jestjs.io/docs/es6-class-mocks#mocking-non-default-class-exports 。
我的意思是,一旦创建了PropertyBasedCachemockImplementation
的新实例并因此应该定义它,就不应该调用我的自定义函数?get/set
解决方案
推荐阅读
- parsing - FParsec 和 pipe3 使参数显式或添加类型表示法
- javascript - 将一个组件的值传递给另一个 Angular
- c# - 找不到文件时由应用程序处理的自定义错误页面
- matlab - 如何使用 MATLAB 在 50 个连续值后分隔文本文档中的 0 和 1
- java - 当移动设备没有任何互联网时,无法从 url 获取 favicon,或者是否可以保存在内部存储中,然后从那里读取
- kdb - 如何使用 each 将变量集传递给 q 中的函数
- php - 如何从数组内部的数组中查找值?
- android - 更新后 Android Studio SDK 安装问题
- ios - 保存主对象上下文时 CoreData 崩溃
- tsql - 在 SQL 中将一行拆分为具有最大列值的多行