简体   繁体   English

jest-mock-extended - 使用 object 输入调用模拟 [Typescript]

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

I'm using jest-mock-extended in my tests.我在测试中使用了jest-mock-extended

I would like to test the following code:我想测试以下代码:

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
}

And my test:我的测试:

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)
})

But since the calledWith function is using referential equality it doesn't work, the compose function of the mocked object returns undefined .但是由于calledWith function 使用引用相等它不起作用,所以模拟 object 的compose function 返回undefined Is there a way to make it work?有没有办法让它工作? Maybe to enforce a shallow equality ?也许是为了强制执行肤浅的平等 I would like to be able to use the calledWith function with an object, is there a way?我希望能够使用被称为calledWith和 object 的调用,有没有办法? Is there another way to mock the compose function according to its input?是否有另一种方法可以根据输入来模拟 compose function?

I think you should use containsValue('value') matcher from jest-mock-extended我认为您应该使用jest-mock-extended containsValue('value')匹配器

in eg.ts fileeg.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
    }
}

in eg.test.ts fileeg.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")
})

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM