使用 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...