代码之家  ›  专栏  ›  技术社区  ›  dsp_099

如何在React构造函数中使用Jest/Enzyme模拟文档对象?

  •  0
  • dsp_099  · 技术社区  · 7 年前

    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;
      }  
    }
    

    enter image description here

    如果我要用酶的话 mount(<WuTangClan />) getCookie . 这是一个问题——该函数依赖于 document 因为jest是在node的上下文中运行的,所以我似乎无法模拟它。意思 文件 当Jest测试运行时是空的,所以我无法让它跳入。

    我试过了所有的答案 this post

    开玩笑“~22.2.2” 酶“^2.5.0”

    1 回复  |  直到 7 年前
        1
  •  0
  •   shmit    7 年前

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

    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;
      });
    推荐文章