【问题标题】:How to mock document object with Jest / Enzyme in a React constructor?如何在 React 构造函数中使用 Jest / Enzyme 模拟文档对象?
【发布时间】:2019-05-25 18:14:01
【问题描述】:

我正在尝试为一些看起来像这样的 React 代码改进代码覆盖率:

export default class WuTangClan {
  constructor(props) {
    super(props);
    this.setState(this.getCookie('36chambers'));
  }

  getCookie(name) {
    const value = `;${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    let toReturn;
    if (parts.length === 2) {
      toReturn = parts
        .pop()
        .split(';')
        .shift();
    }
    return toReturn;
  }  
}

这是我正在努力解决的 codecov 中的一段:

使用酶,如果我去mount(<WuTangClan />),它会运行到getCookie。这是问题 - 该函数依赖于document,并且因为 jest 在节点的上下文中运行,我似乎无法模拟它。意思是,当 Jest 测试运行时,document 是空的,所以我无法让它进入。

我已经尝试了this post 中的所有答案,但均无济于事。

开玩笑“~22.2.2” 酶“^2.5.0” 节点“8.8.0”

【问题讨论】:

  • 您是否尝试过在测试运行之前导入 JSDom 并将 window.document 设置为 jsdom 模拟?

标签: reactjs unit-testing mocha.js jestjs enzyme


【解决方案1】:

如果您唯一的问题是设置 cookie,那么您可以按照以下方式进行:

it("should return cookie", () => {
    global.document.cookie = "cookie1=foo"; //set cookies in whatever format you like
    document.cookie = "cookie2=bar";
    let page = shallow(<WuTangClan />);
    
    // run assertions here;
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-19
    • 2019-08-12
    • 2020-04-22
    • 2019-12-09
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    相关资源
    最近更新 更多