html - 如何在玩笑中更改身体属性?
问题描述
我正在尝试为我的反应组件编写一个测试用例。如果 body 标签的某个属性具有特定值,则渲染 react 组件。这是基于服务动态生成的。我怎样才能开玩笑地修改这个属性,以便我可以渲染我的组件?
到目前为止,我已经尝试过了
window.history.pushState(
{},
"coolvalue",
"coolvalue/"
);
和
// base path for coolvalue
document.body.setAttribute("data-basepath", "coolvalue");
两者似乎都不起作用。
解决方案
以下是修改attribute
of的示例document.body
:
index.ts
:
export function render() {
if (document.body.getAttribute('data-basepath') === 'coolvalue') {
return 'My Component';
}
return null;
}
index.spec.ts
:
import { render } from './';
describe('render', () => {
test('should render my component', () => {
document.body.setAttribute('data-basepath', 'coolvalue');
const actualValue = render();
expect(actualValue).toBe('My Component');
});
it('should not render my component', () => {
document.body.setAttribute('data-basepath', '');
const actualValue = render();
expect(actualValue).toBeNull();
});
});
覆盖率 100% 的单元测试结果:
PASS src/stackoverflow/58365044/index.spec.ts (8.322s)
render
✓ should render my component (11ms)
✓ should not render my component (1ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 10.205s
推荐阅读
- python - 生成器/迭代器的输出在 for 循环之后消失了
- julia - 如何根据function和argtypes获取julia代码的exprs?
- flutter - 如何使堆栈中的孩子在颤动中的高度相等?
- spring-boot - Spring Security Authentication 和 Principal 对象在控制器的方法中来自哪里?
- react-devtools - react devtools 扩展中缺少交互选项卡
- function - 宏提取定义的函数名
- javascript - 将 Click 事件处理程序添加到 Leafletjs 中的标记
- mp4 - 如何将奖励系统放入 pendrive
- python - 堆积图与冲积图相结合 - python
- function - 扩展 lambda 接受错误的参数