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

标签 typescript jestjs equality ts-jest jest-mock-extended

我正在使用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 函数返回 undefined。 有办法让它发挥作用吗?也许是为了强制执行 shallow equality ? 我希望能够将 usedWith 函数与对象一起使用,有什么办法吗? 还有另一种方法可以根据输入来模拟 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")
})

关于typescript - jest-mock-extended - 使用对象输入调用模拟 [Typescript],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67909116/

相关文章:

reactjs - 在 typescript 中使用 defaultProps 的 forwardRef

javascript - SAP cloud sdk for javascript multiple and filters直接附加: leads to "Expression can not converted into ABAP select options" on backend

javascript - 导入自动调用函数将 this 绑定(bind)到 window 对象

javascript - 如果没有鼠标点击事件,我如何对 onClick 进行单元测试?

javascript - 如何测试 useState 钩子(Hook)是否已使用 jest 和 React 测试库调用?

python - 对三个对象使用 "=="运算符

c - C == 运算符如何确定两个浮点值是否相等?

reactjs - 'HTMLElement | null' 类型的参数不能分配给 'Element' 类型的参数。类型 'null' 不可分配给类型 'Element' .ts(2345)

JavaScript 相等运算符给出错误结果?

javascript - RxJs - 具有 Observable 属性的 FlatMap 对象