我用Jest做测试。
我想测试myFunction( myArray )是否没有副作用:
test("that there are no side-effects" ...)如何编写myArray不被myFunction更改的Jest测试
编辑:
我期待一个Jest测试脚本的形式的答案,我想对任何函数和变量,而不仅仅是myFunction( myArray ),使用副作用测试算法。
文件: myFunction.js
export default myFunction;
function myFunction( array ) {
//any code goes here
//maybe it changes array
//maybe it doesn't
//maybe it returns a value
//maybe it doesn't
}文件: myFunction.test.js
import myFunction from "myFunction.js";
test("that there are no side-effects",
//the Jest test code goes here
//where I pass myArray into myFunction
myFunction( myArray )
//myArray should not be changed by myFunction
//what should the test code be?
);发布于 2022-07-02 23:58:34
在严格模式中,可以在测试函数之前对数组进行冰冻,任何直接的突变都会引发异常:
注意,下面代码中的数组元素是原语,但是要防止嵌套对象(包括数组)的突变,还需要冻结这些对象。
<script type="module">
function test (name, fn) {
try {
fn();
console.log('✅', name);
}
catch (ex) {
console.log('❌', name);
console.log(String(ex));
}
}
function doubleArrayValues (array) {
for (let i = 0; i < array.length; i += 1) {
array[i] *= 2;
}
}
function myFunctionPure (array) {
const copy = [...array];
doubleArrayValues(copy);
return copy;
}
function myFunctionImpure (array) {
doubleArrayValues(array);
return array;
}
test('myFunctionPure: has no side-effects', () => {
const myArray = Object.freeze([1, 2, 3]);
myFunctionPure(myArray);
});
test('myFunctionImpure: has no side-effects', () => {
const myArray = Object.freeze([1, 2, 3]);
myFunctionImpure(myArray);
});
</script>
发布于 2022-07-15 19:00:45
我喜欢@jsejcksn的详尽回答。以下是一个快速的答案:
import myFunction from "myFunction.js";
test("that there are no side-effects", () => {
const myArray = [1,2,3];
const myArrayCopy = [...myArray];
const result = myFunction( myArray );
//If the function returns an array,
//it should not be the same reference
expect( result ).not.toBe( myArray );
//The original array values should remain the same
expect( myArray ).toEqual( myArrayCopy );
});https://stackoverflow.com/questions/72842806
复制相似问题