首页 > 解决方案 > 开玩笑:类模拟不使用 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

标签: typescriptjestjscreate-react-app

解决方案


推荐阅读