微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 sinon 对 TypeScript void 函数进行单元测试

如何解决使用 sinon 对 TypeScript void 函数进行单元测试

我正在开发 VS Code 扩展,目前我正在进行单元测试。我对单元测试完全陌生,我完全不知道应该如何对 void 函数进行单元测试。

export const getChecklistItems = async (id: number): Promise<any> => {
  const checklistItems: ChecklistItem[] = [];
  const items: any[] = await getItemsFromUrl(`path_to_url/{id}`);

  items.map((item) => checklistItems.push(new ChecklistItem(item.checklist_items_id,item.checklist_items_content)));

  return checklistItems;
};

export const onSelectInsertComment = async (id: number): Promise<void> => {
  const editor: TextEditor | undefined = window.activeTextEditor;
  const items: any[] = await getChecklistItems(id);

  items.reverse(); // Workaround to output comments in correct numerical order inside the TextEditor

  if (!editor) {
    window.showWarningMessage('No editors are open in you workspace');
  } else {
    items.forEach((item) => {
      editor?.insertSnippet(new SnippetString(`$LINE_COMMENT ${item.label}\n`));
    });

    window.showinformationMessage('Great. Checklist items have been inserted');
  }
};

我在单元测试中使用 mocha、chai 和 sinon。我正在尝试使用间谍来检查在调用 getCheckListItems(id) 时是否调用onSelectInsertComment(id)。我尝试过的一件事如下:

describe('#onSelectInsertComment',() => {
  it('should be resolved',() => {
    const id = 1;
    const spy = sinon.spy(getChecklistItems);
    spy.withArgs(id);

    onSelectInsertComment(id);

    sinon.assert.calledOnce(spy);
  });
});

结果是: AssertError: expected getChecklistItems to be called once but was called 0 times

我做错了什么?如果我被指出正确的方向,我将不胜感激。谢谢。

解决方法

注意事项:

  • 我不知道这是否适用于 VSCode 扩展,但这适用于带有 sinon 的普通打字稿项目。
  • 例如:我假设 getChecklistItemsonSelectInsertComment 在同一个文件中:util.ts。

在你的测试中,而不是使用这个导入:

import { getChecklistItems,onSelectInsertComment } from './util';

使用这个:

import * as util from './util';

并将您的测试代码更改为:

import sinon from 'sinon';
import * as util from './util';

describe('#onSelectInsertComment',() => {
  it('should be resolved',() => {
    const id = 1;
    const spy = sinon.spy(util,'getChecklistItems');
    spy.withArgs(id);

    util.onSelectInsertComment(id);

    sinon.assert.calledOnce(spy);
  });
});

为什么?

因为在你的原始代码中,你使用sinon spy来包装你的函数getChecklistItems,但是函数onSelectInsertComment已经定义了,并没有使用spy定义的,而是使用原来的getChecklistItems。您可以查看参考文献 1

参考资料

  1. Sinon How to Stub Dependency
  2. Sinon Spy Method Signature

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?