Unit Testing Sitemap generated by Next page
Unanswered
Clark's Grebe posted this in #help-forum
Clark's GrebeOP
I'm generating sitemaps by having a root sitemap that checks through the
All is working fine; however, I am struggling to get any tests working on it to prevent regression. Any help appreciated - some code snippets below to help paint the picture
fs
to get the page structure for other sitemaps within the /sitemaps/
folder and creates a sitemapindex
entry per sitemap. It does this within getServerSideProps
each other's sitemap does the same to generate the urlset sitemapAll is working fine; however, I am struggling to get any tests working on it to prevent regression. Any help appreciated - some code snippets below to help paint the picture
const generateSitemap = (pagesXml: string) => {
return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${pagesXml}
</urlset>`;
};
const generateSitemapIndex = (pagesXml: string) => {
return `<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${pagesXml}
</sitemapindex>`;
};
export const writeSitemap = (contents: string, type: 'urlset' | 'sitemapindex', context: GetServerSidePropsContext) => {
const { res } = context;
res.setHeader('Content-Type', 'text/xml');
if (type === 'urlset') {
res.write(generateSitemap(contents));
} else if (type === 'sitemapindex') {
res.write(generateSitemapIndex(contents));
}
res.end();
};
export const getServerSideProps: GetServerSideProps = async (context) => {
const pages = [];
const data = await fetchData();
if (data) {
Object.keys(data).forEach((item) => {
Object.keys(data[item]).forEach((l10n) => {
pages.push(baseUrl + routes.page(item.slug);
});
});
const uniquePages = Array.from(new Set(pages));
const pages = uniquePages
.map(
(url) =>
`<url>
<loc>${url}</loc>
<priority>0.7</priority>
<changefreq>daily</changefreq>
</url>`
)
.join('');
writeSitemap(pages, 'urlset', context);
}
return {
props: {},
};
};