我的测试套件是Jest。
如何多次测试函数是否返回函数是否按预期返回值。我将编写计算数字序列的运行中位数的函数。也就是说,给定一连串数字,请在每个新元素上打印出到目前为止列表的中位数。
例如 [2,1,5,7,2,0,5]
函数应该返回
2([2]的中位数)
1.5([2,1] => [1,2]的中位数)
2([2,1,5]的中位数=> [1,2,5]排序后)
3.5([2,1,5,7]的中位数=> [1,2,5,7]排序后)
2([2、1、5、7、2]的中位数=> [1、2、2、5、7]排序后)
2([2,1,5,7,2,0]的中位数=> [0,1,2,2,5]排序后)
2([2,1,5,7,2,0,5]的中位数=> [0,1,2,2,5,5,7]排序后)
在我的测试套件中
import { Main } from "./main";
describe('', () => {
const main = new Main();
main.main([2, 1, 5, 7, 2, 0, 5]);
beforeEach(() => {
const spyOnMain = jest.spyOn(main, 'second');
});
test('test', () => {
expect(spyOnMain).toHaveBeenCalledTimes(7)
expect(spyOnMain).toHaveReturnedWith([ 2, 1, 5, 7, 2, 0 ])
expect(spyOnMain).toHaveReturnedWith([ 2, 1, 5, 7, 2 ])
});
});
在我要测试的js文件中
export class Main {
// Your code begins here;
main(arr) {
while (arr.length > 0) {
arr.pop();
this.second(arr)
this.main(arr);
}
}
second(arr) {
console.log(arr);
return arr
}
}