Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrest state when testing with renderHook #148

Closed
kostrse opened this issue Aug 19, 2019 · 2 comments
Closed

Incorrest state when testing with renderHook #148

kostrse opened this issue Aug 19, 2019 · 2 comments
Labels
bug Something isn't working

Comments

@kostrse
Copy link

kostrse commented Aug 19, 2019

I was trying to test behavior of the useAsync hook using the renderHook from the testing-library/react-hooks, and found the following issues (which is probably I'm trying to use the library in a wrong way).

First, when hook returns it's initial state, it returns initialValue (as expected), but it also indicates that the promise has been already resolved:

it('should set into proper initial state', async () => {
    const asyncFunc = () => Promise.resolve(2);

    const { result } = renderHook(() => useAsync(asyncFunc, { initialValue: 1 }));

    expect(result.current.value).toEqual(1);
    expect(result.current.isResolved).toBe(false); // FAILS, ALREADY RESOLVED
});

I expected it to be either { data: 1, isResolved: false }, or { data: 2, isResolved: true }.

Second issue, is that for some reason the waitForNextUpdate never resolve:

it('should resolve resolved promise', async () => {
    // already resolved
    const asyncFunc = () => Promise.resolve(2);

    const { result, waitForNextUpdate } = renderHook(() => useAsync(asyncFunc, { initialValue: 1 }));

    expect(result.current.value).toEqual(1);

    await waitForNextUpdate(); // NEVER RESOLVE
});

it('should resolve asynchronous promise', async () => {
    // will resolve in 50ms
    const asyncFunc = () => new Promise(resolve => setTimeout(resolve, 50)).then(() => 2);

    const { result, waitForNextUpdate } = renderHook(() => useAsync(asyncFunc, { initialValue: 1 }));

    expect(result.current.value).toEqual(1);

    await waitForNextUpdate(); // NEVER RESOLVE
});

This is probably related to the first issue - promise is in resolved state already but the value from the promise wasn't set.

@kostrse kostrse added the bug Something isn't working label Aug 19, 2019
@mpeyper
Copy link
Member

mpeyper commented Aug 19, 2019

Can you share the useAsync hook code as well please? (Preferably in a codesandbox)

@kostrse
Copy link
Author

kostrse commented Aug 19, 2019

I'm sorry, I had intention to post it to react-async, posted by mistake here. I believe the issue is with react-async, not @testing-library/react-hooks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants