javascript - 如果使用 Ramda reduce 但使用 native 则 Jest 测试失败

标签 javascript unit-testing jestjs ramda.js babel-jest

我注意到,如果我使用 ramda,有时我会在尝试为我正在导出的方法编写 Jest 测试时遇到问题。我已经将问题归结为以下测试和两个基本的 reducer 功能。我已将它们发布在 gist 上,以免代码阻塞这个问题。

https://gist.github.com/beardedtim/99aabe3b08ba58037b20d65343ed9d20

我在使用 ramda reducer 时遇到以下错误:

      ● counter usage › counter counts the words and their index in the given list of words

    expect(received).toEqual(expected)

    Expected value to equal:
      [{"count": 3, "indexes": [0, 2, 4], "value": "a"}, {"count": 1, "indexes": [1], "value": "b"}, {"count": 1, "indexes": [3], "value": "c"}]
    Received:
      [{"count": 15, "indexes": [0, 2, 4, 0, 2, 4, 0, 2, 4, 0, 2, 4, 0, 2, 4], "value": "a"}, {"count": 5, "indexes": [1, 1, 1, 1, 1], "value": "b"}, {"count": 5, "indexes": [3, 3, 3, 3, 3
], "value": "c"}]

这让我相信 ramda 的 reduce 是保持某种状态或彼此共享 words。我不确定这是怎么回事。任何人都知道我应该用谷歌搜索什么或其他人处理这个的一些文档/示例?

最佳答案

状态数组(final)被硬连接到 reduceWithIndex 中。对此函数的所有调用共享相同的 final 数组。

试试这个:

import { reduce, addIndex } from 'ramda';

const reduceWithIndex = addIndex(reduce)((final, word, index) => {
  const found = final.find(({ value }) =>
    value.toLowerCase() === word.toLowerCase()
  );
  if (found) {
    found.count++;
    found.indexes.push(index);
  } else {
    final.push({
      value: word.toLocaleLowerCase(),
      count: 1,
      indexes: [index],
    });
  }

  return final;
});

export default words => reduceWithIndex([], words);

关于javascript - 如果使用 Ramda reduce 但使用 native 则 Jest 测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43443833/

相关文章:

javascript - 如何编写嵌套 v-for 循环来显示所有元素?

java - 为可测试性设计构造函数

python - pytest 和 codecov : no coverage report found

java - Robolectric 测试从小部件启动的 Activity

javascript - 如何测试调度自定义事件的方法

javascript - 自动计算返回未定义

javascript - 根据键码更改数组

javascript - 使用过滤器 css 属性调整传单 map 的亮度

javascript - Jest : How to test for optional object keys

javascript - 使用 jest 模拟 moment() 和 moment().format