如何使用jest和enzyme在react中测试componentDidMount with has document.getElementByClassName?

yvt65v4c  于 2023-04-10  发布在  Jest
关注(0)|答案(1)|浏览(140)

嗨,我试图测试功能使用React16与jest和酶,我已经写了测试用例,请看看下面的代码,我已经写了,我也试图测试。任何建议将是很大的帮助。

我想测试什么?

componentDidMount() {
if (this.props.isSubmissionComplete) {
  window.location.href = process.env.REACT_APP_BASE_PATH;
}

if (document.getElementsByClassName("continue-button")[0]) {
  document
    .getElementsByClassName("continue-button")[0]
    .classList.add("hidden");
}
if (document.getElementsByClassName("back-button")[0]) {
  document
    .getElementsByClassName("back-button")[0]
    .classList.remove("offset-sm-1");
}

//Sets the applicable coverages to the state for use in the post submission pages
var coverageList = this.renderCoverageList();
this.props.updateApplicableCoverages(coverageList);
  }

我写的代码是为了测试。

let wrapper;

  beforeEach(() => {
    wrapper = mount(
      <FraudStatement/>
    );
  });

 it("should hide the continue button if it exists", () => {

expect(wrapper.find(".continue-button").hasClass("hidden")).toBe(true);
  });

我得到的错误

Error: expect(received).toBe(expected) // Object.is equality

Expected: true
Received: false Jest
kwvwclae

kwvwclae1#

说明

基本上这里我尝试在DOM中创建一个新元素,用s浅渲染组件,然后测试if条件,如果条件满足,它将期望Assert语句。
测试时,代码还标记100%的代码覆盖率。

const continueButton = document.createElement("button");
continueButton.classList.add("continue-button");
document.body.appendChild(continueButton);

const wrapper = shallow(<FraudStatement />);
const buttonWrapper = wrapper.find(".continue-button");
if (!buttonWrapper.exists()) {
  return;
}
const isHidden = buttonWrapper.hasClass("hidden");
expect(isHidden).toBe(true);
document.body.removeChild(continueButton);

相关问题