【问题标题】:jest-mock-extended - call mock with object input [Typescript]jest-mock-extended - 使用对象输入调用模拟 [Typescript]
【发布时间】:2021-08-26 18:01:39
【问题描述】:

我在测试中使用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? 我希望能够将calledWith 函数与对象一起使用,有没有办法? 是否有另一种方法可以根据输入来模拟 compose 函数?

【问题讨论】:

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


    【解决方案1】:

    我认为你应该使用来自jest-mock-extendedcontainsValue('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")
    })
    

    【讨论】:

    • 像魅力一样工作,tnx
    猜你喜欢
    • 2023-02-17
    • 2021-06-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多