Javascript 使用sinon对TypeScript void函数进行单元测试
我正在开发VS代码扩展,目前正在进行单元测试。我对单元测试是完全陌生的,我完全不知道应该如何对一个空函数进行单元测试Javascript 使用sinon对TypeScript void函数进行单元测试,javascript,typescript,unit-testing,sinon,vscode-extensions,Javascript,Typescript,Unit Testing,Sinon,Vscode Extensions,我正在开发VS代码扩展,目前正在进行单元测试。我对单元测试是完全陌生的,我完全不知道应该如何对一个空函数进行单元测试 export const getChecklistItems = async (id: number): Promise<any> => { const checklistItems: ChecklistItem[] = []; const items: any[] = await getItemsFromUrl(`path_to_url/{id}`);
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');
}
};
结果是:AssertError:预期会调用一次getChecklistItems,但调用了0次
我做错了什么?如果能给我指出正确的方向,我将不胜感激。谢谢。注意:
- 我不知道这是否适用于VSCode扩展,但这适用于使用sinon的普通typescript项目
- 例如:我假设getChecklistItems和onSelectInsertComment都在同一个文件中: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。你可以查看参考资料
参考资料
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);
});
});