我正在使用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/