首页 > 解决方案 > 笑话:模拟高阶函数

问题描述

我正在尝试模拟第三方库以使用 Jest 编写集成测试

产品。代码部分:

const processedContent = await remark().use(html).process(content);

所以我想将备注模拟为一个 HOF 来返回一个函数(使用)来返回另一个函数(进程)

我的做法:

remark.mockImplementationOnce(() => {
      return function use() {
        return function process() {
          return testMessageContent;
        };
      };
    })

因此,如果 console.log(remark) 我可以看到它如何返回一个函数,但是当我尝试 console.log(remark().use() 时,我得到:

TypeError: (0 , _remark.default)(...).use is not a function

  72 |     //const ans = await addReply(content, comment, userInfo._id);
  73 | 
> 74 |     console.log(remark().use());

如果我:

const use = remark()
const process = use()
const message = process()

一切正常。我不明白为什么这不起作用。任何帮助将不胜感激!

提前致谢!

标签: unit-testingjestjsmockingintegration-testing

解决方案


模拟不会返回带有use方法的对象,并且调用的命名函数use不会改变它的工作方式。

它应该是:

remark.mockImplementationOnce(() => {
      return { use() {
        return { process() {
          return testMessageContent;
        } };
      } };
    })

推荐阅读