首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Jest和JavaScript测试一个副作用函数

如何使用Jest和JavaScript测试一个副作用函数
EN

Stack Overflow用户
提问于 2022-07-02 22:26:03
回答 2查看 266关注 0票数 1

我用Jest做测试。

我想测试myFunction( myArray )是否没有副作用:

代码语言:javascript
复制
test("that there are no side-effects" ...)

如何编写myArray不被myFunction更改的Jest测试

编辑:

我期待一个Jest测试脚本的形式的答案,我想对任何函数和变量,而不仅仅是myFunction( myArray ),使用副作用测试算法。

文件: myFunction.js

代码语言:javascript
复制
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

代码语言:javascript
复制
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?
);
EN

回答 2

Stack Overflow用户

发布于 2022-07-02 23:58:34

严格模式中,可以在测试函数之前对数组进行冰冻,任何直接的突变都会引发异常:

注意,下面代码中的数组元素是原语,但是要防止嵌套对象(包括数组)的突变,还需要冻结这些对象。

代码语言:javascript
复制
<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>

票数 1
EN

Stack Overflow用户

发布于 2022-07-15 19:00:45

我喜欢@jsejcksn的详尽回答。以下是一个快速的答案:

代码语言:javascript
复制
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 );
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72842806

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档