jestjs - jest-mock-extended - 使用对象输入调用模拟 [Typescript]
我在测试中使用 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 函数使用的是引用相等,它不起作用,模拟对象的 compose 函数返回 undefined。有没有办法让它起作用?也许可以强制使用浅层相等?我希望能够对一个对象使用 calledWith 函数,有办法吗?或者根据输入还有其他方法来模拟 compose 函数吗?
答案#1
我认为你应该使用 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")
})
