headstartwp
headstartwp copied to clipboard
Improve unit tests
Is your enhancement related to a problem? Please describe.
Currently, most fetch calls are not mocked and instead are handled with msw. Due to how things are architected the sourceUrl removal doesn't work in tests (removeSourceUrl
) which makes testing post/category path mapping hard and not ideal.
Additionally, useSWR cache is persisting across tests which could lead to tests passing without actually executing the query on the test, which is problematic when the data the test expects is the same but there should be additional processing post-fetch.
For example, the second test below will never pass, but if you only run the second it does pass. The reason is bc the second test is reusing the cached result from the first instead of re-running the query AND the logic post-query.
it('returns queried object for category archives', async () => {
const { result } = renderHook(
() =>
useFetchPosts({
category: 'uncategorized',
per_page: 1,
}),
{
wrapper,
},
);
await waitFor(() => {
expect(result.current.data?.posts.length).toBe(1);
expect(result.current.data?.queriedObject.term?.slug).toBe('uncategorized');
expect(result.current.pageType.isAuthorArchive).toBe(false);
expect(result.current.pageType.isCategoryArchive).toBe(true);
expect(result.current.pageType.isSearch).toBe(false);
expect(result.current.pageType.isTaxonomyArchive).toBe(true);
expect(result.current.pageType.isTagArchive).toBe(false);
});
});
it('throws matchArchivepath config option is true and path does not match', async () => {
setHeadlessConfig({
useWordPressPlugin: true,
customTaxonomies: (defaultTaxonomies) => {
return defaultTaxonomies.map((taxonomy) => ({
...taxonomy,
matchArchivePath: true,
}));
},
});
const { result } = renderHook(
() =>
useFetchPosts(
{
category: 'uncategorized',
per_page: 1,
},
{},
'/category/asdasd/uncategorized',
),
{
wrapper,
},
);
await waitFor(() => {
expect(result.current.error?.toString()).toBe(
`NotFoundError: Posts were found but did not match current path: "/category/asdasd/uncategorized"`,
);
});
});
The solution to the useSWR caching issue is to clear the cache between every test.
Designs
No response
Describe alternatives you've considered
No response
Code of Conduct
- [X] I agree to follow this project's Code of Conduct