我有两个模拟简单的求和运算的类。
import SumProcessor from "./SumProcessor";
class Calculator {
constructor(private _processor: SumProcessor) { }
sum(a: number, b: number): number {
return this._processor.sum(a, b)
}
}
export default Calculator
还有运算处理器。
class SumProcessor {
sum(a: number, b: number): number {
return a + b
}
static log() {
console.log('houston...')
}
}
export default SumProcessor
我正在尝试模拟SumProcessor类,以使用jest + ts-jest编写以下单元测试。
import Calculator from "./Calculator"
import SumProcessor from "./SumProcessor"
import { mocked } from "ts-jest/utils"
jest.mock('./SumProcessor')
describe('Calculator', () => {
it('test sum', () => {
const SomadorMock = <jest.Mock>(SumProcessor)
SomadorMock.mockImplementation(() => {
return {
sum: () => 2
}
})
const somador = new SomadorMock()
const calc = new Calculator(somador)
expect(calc.sum(1, 1)).toBe(2)
})
})
当SumProcessor类中存在静态方法时,模拟代码const SomadorMock =(SumProcessor)表示以下编译错误:
TS2345: Argument of type '() => jest.Mock<any, any>' is not assignable to parameter of type '(values?: object, option
s?: BuildOptions) => SumOperator'.
Type 'Mock<any, any>' is missing the following properties from type 'SumOperator...
如果从SumProcessor类中删除了静态方法,则一切正常。
有人可以帮忙吗?
答案 0 :(得分:2)
由于您已经用<div class="timeline"></div>
<div class="timeline"></div>
<div class="timeline"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
模拟了SumProcessor
类,因此您可以在想要模拟的方法中添加一个间谍,例如:
jest.mock('./SumProcessor');
这样,您的测试类将如下所示:
jest.spyOn(SumProcessor.prototype, 'sum').mockImplementation(() => 2);
简单得多,对吧?