JEST component testing

后端 未结 2 1150
说谎
说谎 2020-12-22 00:44

I am new to unit testing with Jest. I am testing a component in a React app. There are two components: Home and LogOutButton

This is The Ho

相关标签:
2条回答
  • 2020-12-22 01:09

    It's hard to tell how your code will behave without seeing the code for your LogOutButton component. But here are a couple of pointers:

    First of all, note that your test simulates a 'ckick' event and not a click event as your probably meant.

    Second point is that .html is a function so you should add parentheses to it in your test: .html().

    Third point is that the call to homeWrapper.update() seems redundant.

    Lastly and most importantly, even if your component works as intended, the result of clicking the LogOutButton would be a page redirect to https://www.MICROSOFT.com.

    Even if the redirect worked - which I don't think it will, since your test does not run in a real browser - there's no reason to expect that a call to homeWrapper.html() would return the URL. It would return the HTML that makes up the rendered component.

    In your case, you can expect the call to homeWrapper.html() to return something like:

    <div><h1>Hello world! The result is: 0</h1><input type=\"text\"/>+<input type=\"text\"/>= <br/><button>Add</button><br/><br/><button id=\"x\">LogOut</button></div>
    

    This of course, does not prove that onLogoutClick worked correctly. Instead, you might consider replacing onLogoutClick with a Jest Mock in your test and then expect the mock to have been called once.

    0 讨论(0)
  • 2020-12-22 01:31

    A fix for your test is a little addition to what you already have.

    delete window.location;
    window.location = { reload: jest.fn() };
    
    describe('Home', () => {
      it('should click logout button', () => {
        const component = Enzyme.mount(<Home />);
        const logOutButton = component.find(LogOutButton);
        logOutButton.simulate('click');
        expect(window.location.href).toEqual('https://www.MICROSOFT.com');
      });
    });
    

    You quickly notice I deleted window.location as window.location is not modifiable in Jest. That is the missing link.

    0 讨论(0)
提交回复
热议问题