0

I am trying to improve codecoverage for a bit of React code which looks kind of like this:

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

Here's the piece from codecov which I'm struggling with:

enter image description here

Using enzyme, if I were to mount(<WuTangClan />), it would then run through getCookie. Here's issue - that function relies on document and because jest runs in the context of node I can't seem to mock it. Meaning, document is empty when Jest tests are running and so I can't get it to jump in.

I've tried every answer in this post to no avail.

Jest "~22.2.2" Enzyme "^2.5.0" Node "8.8.0"

skyboyer
  • 22,209
  • 7
  • 57
  • 64
dsp_099
  • 5,801
  • 17
  • 72
  • 128
  • Have you tried importing JSDom and setting window.document equal to the jsdom mock before your tests run? – johnslay Dec 27 '18 at 20:04

1 Answers1

0

If your only issue is about setting cookies then you can do so like below:

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;
  });
shmit
  • 2,306
  • 2
  • 16
  • 20