【问题标题】:Unit test a TypeScript void function with sinon使用 sinon 对 TypeScript void 函数进行单元测试
【发布时间】:2021-07-16 22:06:18
【问题描述】:

我正在开发一个 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 进行单元测试。我正在尝试使用间谍检查在调用onSelectInsertComment(id) 时是否调用了getCheckListItems(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

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

【问题讨论】:

    标签: javascript typescript unit-testing sinon vscode-extensions


    【解决方案1】:

    注意事项:

    • 我不知道这是否适用于 VSCode 扩展,但这适用于带有 sinon 的普通 typescript 项目。
    • 例如:我假设 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-08
      • 1970-01-01
      • 2020-08-13
      • 2016-12-21
      • 2021-03-15
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      相关资源
      最近更新 更多