How to use Jest to test React rendered async data?

霸气de小男生 提交于 2020-01-03 15:36:23

问题


I am using React for render and Jest/Jasmine for test. I have test written using old Jest/Jasmine waitsFor and runs but these are gone now in Jasmine 2 and I am not sure how to replace with new done asyncs.

In my code React renders a small page about a user. That page has an AJAX call to fetch user posts. I want to test that user posts have come back nice, and waitsFor was very, very good at this: wait until user has some post, then continue.

I looked online at lots of people talking about using AJAX calls inside Jest test which is not what I want. My Jest test has no idea about AJAX call being made, so I need a way to wait until results come back.

Here is my current code with waitsFor and runs:

it('loads user post', () => {
    var page = TestUtils.renderIntoDocument(
        <UserPage params={{user: 'fizzbuzz', 'pass': 'xxx'}} />
    );

    waitsFor(() => {
        return page.state.posts.length > 0;
    }, "post loaded", 10000);

    runs(() => {
        var posts = TestUtils.scryRenderedDOMComponentsWithClass(page, 'post');
        expect(posts.length).toEqual(10);
    });
});

How can I delete the waitsFor and runs and replace with Jasmine 2.0 code that works? All Jest test knows is that page.state.posts.length must be greater than 0 before expecting anything.


回答1:


You should refactor this test into two unit tests that will provide a more rigorous testing of your code. It would make the tests more independent of one another and help identify errors in a more refined scope. These won't be exact as I do not know what your code is like, but here's something along the lines I would expect to see: -

it('generates the expected properties for a page', function () {
    var page = TestUtils.renderIntoDocument(
        <UserPage params={{user: 'fizzbuzz', 'pass': 'xxx'}} />
    );

    expect(page.someProperty).toBeDefined();
    expect(page.user).toEqual('fizzbuzz');
});

it('generates the correct number of posts from a given page object', function () {
    var fakePage = {
        // put your fake mock data here that TestUtils expects
    };

    var posts = TestUtils.scryRenderedDOMComponentsWithClass(fakePage, 'post');

    expect(posts.length).toEqual(10);
});

I am not too sure what is happening in your renderIntoDocument function so the top test may be a little broken... It looks like there is either too much going on inside the function, or you need to test the calls that function is making instead. If you elaborate on what it does I'll edit the answer.



来源:https://stackoverflow.com/questions/37310701/how-to-use-jest-to-test-react-rendered-async-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!