首页 > 解决方案 > 如何在玩笑中更改身体属性?

问题描述

我正在尝试为我的反应组件编写一个测试用例。如果 body 标签的某个属性具有特定值,则渲染 react 组件。这是基于服务动态生成的。我怎样才能开玩笑地修改这个属性,以便我可以渲染我的组件?

到目前为止,我已经尝试过了

window.history.pushState(
  {},
  "coolvalue",
  "coolvalue/"
);

// base path for coolvalue
document.body.setAttribute("data-basepath", "coolvalue"); 

两者似乎都不起作用。

标签: htmlreactjsdomjestjsenzyme

解决方案


以下是修改attributeof的示例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

推荐阅读