angular - 如何在 void 函数中测试对函数范围变量的分配?
问题描述
我有一个函数,由于代码覆盖率,我需要对其进行测试。
const downloadPdfDataContent = (title: string, url: string): void => {
const link = document.createElement('a');
link.target = title;
link.href = url;
link.download = title;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
};
如何完成对变量和文档对象的分配测试?我想我需要使用 spyOn .. 但我不知道具体如何,因为变量只存在于函数范围内。我想过简单地返回变量,但如果可能的话,我想阻止这种情况。
解决方案
您可以使用jest.spyOn()
来模拟每个 DOM 操作。
例如
index.ts
:
export const downloadPdfDataContent = (title: string, url: string): void => {
const link = document.createElement('a');
link.target = title;
link.href = url;
link.download = title;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
};
index.test.ts
:
import { downloadPdfDataContent } from '.';
describe('67634069', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should pass', () => {
const mAnchor = ({
target: '',
href: '',
download: '',
click: jest.fn(),
} as unknown) as HTMLAnchorElement;
const createElementSpy = jest.spyOn(document, 'createElement').mockReturnValueOnce(mAnchor);
const appendChildSpy = jest.spyOn(document.body, 'appendChild').mockImplementation();
const removeChildSpy = jest.spyOn(document.body, 'removeChild').mockImplementation();
URL.revokeObjectURL = jest.fn();
downloadPdfDataContent('teresa teng', 'example.com');
expect(createElementSpy).toBeCalledWith('a');
expect(appendChildSpy).toBeCalledWith(
expect.objectContaining({
target: 'teresa teng',
href: 'example.com',
download: 'teresa teng',
})
);
expect(mAnchor.click).toBeCalledTimes(1);
expect(removeChildSpy).toBeCalledWith(
expect.objectContaining({
target: 'teresa teng',
href: 'example.com',
download: 'teresa teng',
})
);
expect(URL.revokeObjectURL).toBeCalledWith('example.com');
});
});
测试结果:
PASS examples/67634069/index.test.ts (8.691 s)
67634069
✓ should pass (4 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.ts | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.612 s
推荐阅读
- c++ - 使用可变参数模板实现类型列表替换操作
- python - TypeError: __init__() missing 1 required positional argument: ,我该如何解决这个问题?
- python-3.x - 如何在我的 Python 脚本中针对此错误进行调整和调试?
- r - dplyr::tally 与因素和字符
- r - 如果行包含匹配项,则为行中的每个元素添加值
- javascript - bootstraps4下拉按钮中的日历-如果用户单击日历,如何使下拉菜单保持打开状态
- node.js - 如何使用 NODE_ENV 选择连接哪个数据库?
- sql - 如何从 JSON PATH 中获取未转义的值
- python - networkX.draw() 不产生边
- grafana - 获取时间戳的小时数并在 grafana 中显示