【发布时间】: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