Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest test for a copy to clipboard method using react with typescript

I am trying to ensure that the right value is copied to the users clipboard when they click a button. This is my copy method. I am using a ref on the input to access the right value.

  protected copyToClipboard() {
   console.log("clicked!");
   const text = this.controls.copyData;

   if (!_.isNil(text)) {
     text.current.focus();
     text.current.select();

     document.execCommand("copy");
     this.setState({copied: true});
   }
 }

For my test:

  test("Ensure right value is copied to clipboard", () => {
    const wrapper = mount(<MyComponent />);

    const copyButton = wrapper.find(".copyBtn");
    copyButton.simulate("click");

    const copyToClipboardSpy = jest.spyOn(document as any, "execCommand");
    wrapper.update();

    expect(copyToClipboardSpy).toHaveBeenCalledWith("copy");
  });

The error I receive when I run the test is TypeError: document.execCommand is not a function which makes sense, but I am unsure how to approach this.

I am relatively new to testing, just to put that out there. I also have read that I may not be able to access the document.execCommand but have struggled to find a good alternative to hijack the test and access the value being copied. I appreciate any advice that can be given on the matter!

like image 548
suzu94 Avatar asked Dec 11 '22 00:12

suzu94


1 Answers

Posting this in case anyone else was in a similar boat. It's doesn't necessarily check the value yet, but one piece I managed was with the document.execCommand method.

I set up a mock function above the wrapper:

document.execCommand = jest.fn();

With this, the test stopped throwing the TypeError. Then my expectations included checking for the spy to have been called, expect my copy state to have changed to true, and:

expect(document.execCommand).toHaveBeenCalledWith("copy");

Test passes! A possible solution for the value is to see if I can "paste" the value and then check it. Will edit this response if/when I can manage that

like image 171
suzu94 Avatar answered Jan 01 '23 14:01

suzu94