【问题标题】:How to change body attribute in jest?如何在玩笑中更改身体属性?
【发布时间】:2020-02-10 09:15:32
【问题描述】:

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

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

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

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

两者似乎都不起作用。

【问题讨论】:

  • 你能分享一下你想测试的最小代码吗?

标签: html reactjs dom jestjs enzyme


【解决方案1】:

下面是修改attributedocument.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

【讨论】:

    猜你喜欢
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多