jest-mock-extended - 使用对象输入 [Typescript] 调用 mock

jest-mock-extended - call mock with object input [Typescript]

我在测试中使用 jest-mock-extended

我想测试以下代码:

class A {

  constructor(private b: B){}

  public test(x: string): string {

    const res1 = this.b.compose({
      name: x + '_foo'
    })

    const res2 = this.b.compose({
      name: x + '_bar'
    })
  }

  return res1 + '_' + res2
}

我的测试:

test(() => {
  const bMock: MockProxy<B> = mock<B>()
  const a: A = new A(bMock)
  
  bMock.compose.calledWith({
                x: 'yoyo_foo'
            }).mockReturnValueOnce(x + '_once')

  bMock.compose.calledWith({
                x: 'yoyo_bar'
            }).mockReturnValueOnce(x + '_twice')
  //ACT
  const result = a.test('yoyo')

  //ASSERT
  expect(result).toBe('yoyo_foo_once_yoyo_bar_twice)
})

但是由于 calledWith 函数正在使用 referential equality 它不起作用,模拟对象的 compose 函数 returns undefined。 有没有办法让它工作?也许强制执行 shallow equality? 我希望能够对对象使用 calledWith 函数,有什么办法吗? 是否有另一种方法可以根据输入模拟 compose 函数?

我认为你应该使用 jest-mock-extended

中的 containsValue('value') 匹配器

eg.ts 文件中

export interface B {
    compose(obj): string
}

export class A {
    constructor(private b: B) {}

    public test(x: string): string {
        const res1 = this.b.compose({
            name: x + "_foo"
        })

        const res2 = this.b.compose({
            name: x + "_bar"
        })
        return res1 + "_" + res2
    }
}

eg.test.ts 文件中

// libs
import { test, expect } from "@jest/globals"
import { mock, MockProxy, objectContainsValue } from "jest-mock-extended"

import { A, B } from "./eg"

test("test", () => {
    const bMock: MockProxy<B> = mock<B>()
    const a: A = new A(bMock)

    bMock.compose
        .calledWith(objectContainsValue("yoyo_foo"))
        .mockReturnValueOnce("yoyo_foo" + "_once")

    bMock.compose
        .calledWith(objectContainsValue("yoyo_bar"))
        .mockReturnValueOnce("yoyo_bar" + "_twice")
    //ACT
    const result = a.test("yoyo")

    //ASSERT
    expect(result).toBe("yoyo_foo_once_yoyo_bar_twice")
})