Skip to content

Commit

Permalink
Add tests for errorPolicy on useMutation
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesreggio committed Jan 26, 2020
1 parent af0a03f commit 36ec963
Showing 1 changed file with 107 additions and 1 deletion.
108 changes: 107 additions & 1 deletion src/react/hooks/__tests__/useMutation.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DocumentNode } from 'graphql';
import { DocumentNode, GraphQLError } from 'graphql';
import gql from 'graphql-tag';
import { render, cleanup, wait } from '@testing-library/react';

Expand Down Expand Up @@ -39,6 +39,8 @@ describe('useMutation Hook', () => {
}
};

const CREATE_TODO_ERROR = 'Failed to create item';

afterEach(cleanup);

describe('General use', () => {
Expand Down Expand Up @@ -253,6 +255,110 @@ describe('useMutation Hook', () => {
return wait();
});

describe.only('mutate function upon error', () => {
it(`should reject when errorPolicy is 'none'`, async () => {
const variables = {
description: 'Get milk!'
};

const mocks = [
{
request: {
query: CREATE_TODO_MUTATION,
variables
},
result: {
data: CREATE_TODO_RESULT,
errors: [new GraphQLError(CREATE_TODO_ERROR)],
},
}
];

const Component = () => {
const [createTodo] = useMutation<{ createTodo: Todo }>(
CREATE_TODO_MUTATION,
{ errorPolicy: 'none' }
);

async function doIt() {
try {
await createTodo({ variables });
} catch (error) {
expect(error.message).toEqual(
expect.stringContaining(CREATE_TODO_ERROR)
);
}
}

useEffect(() => {
doIt();
}, []);

return null;
};

render(
<MockedProvider mocks={mocks}>
<Component />
</MockedProvider>
);

return wait();
});

it(`should resolve with 'data' and 'error' properties when errorPolicy is 'all'`, async () => {
const variables = {
description: 'Get milk!'
};

const mocks = [
{
request: {
query: CREATE_TODO_MUTATION,
variables
},
result: {
data: CREATE_TODO_RESULT,
errors: [new GraphQLError(CREATE_TODO_ERROR)],
},
}
];

const Component = () => {
const [createTodo] = useMutation<{ createTodo: Todo }>(
CREATE_TODO_MUTATION,
{ errorPolicy: 'all' }
);

async function doIt() {
const { data, errors } = await createTodo({ variables });

expect(data).toEqual(CREATE_TODO_RESULT);
expect(data!.createTodo.description).toEqual(
CREATE_TODO_RESULT.createTodo.description
);
expect(errors[0].message).toEqual(
expect.stringContaining(CREATE_TODO_ERROR)
);
}

useEffect(() => {
doIt();
}, []);

return null;
};

render(
<MockedProvider mocks={mocks}>
<Component />
</MockedProvider>
);

return wait();
})
});

it('should return the current client instance in the result object', async () => {
const Component = () => {
const [, { client }] = useMutation(CREATE_TODO_MUTATION);
Expand Down

0 comments on commit 36ec963

Please sign in to comment.