首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >jest- mock -extended - call mock with object input [Typescript]

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

Stack Overflow用户
提问于 2021-06-10 01:33:55
回答 1查看 538关注 0票数 1

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

我想测试以下代码:

代码语言:javascript
运行
复制
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
}

我的测试是:

代码语言:javascript
运行
复制
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函数?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-10 01:58:08

我认为你应该使用jest-mock-extendedcontainsValue('value') matcher

eg.ts文件中

代码语言:javascript
运行
复制
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文件中

代码语言:javascript
运行
复制
// 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")
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67909116

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档