Skip to content

Instantly share code, notes, and snippets.

@vanduc1102
Last active December 26, 2020 06:37
Show Gist options
  • Save vanduc1102/8f9d4e8439e34ef5b95bfbe1c743423a to your computer and use it in GitHub Desktop.
Save vanduc1102/8f9d4e8439e34ef5b95bfbe1c743423a to your computer and use it in GitHub Desktop.
Jest testing DOM in Node
const fetch = require('node-fetch');
async function getContent(url, originRequest) {
console.log('Getting content from: ', url);
const { redirectUrl } = originRequest.query;
const { host, ...remainingHeaders } = originRequest.headers;
return fetch(url, {
method: originRequest.method,
headers: { ...remainingHeaders},
rejectUnauthorized: false
})
.then(res => res.text());
}
module.exports = {
getContent
};
const fs = require('fs');
const path = require('path');
function getFileContent(filePath) {
return fs.createReadStream(path.resolve(__dirname, filePath));
}
module.exports = {
getFileContent
};
jest.mock('node-fetch');
const fetch = require('node-fetch');
const { JSDOM } = require('jsdom');
const { getContent } = require('./content');
const { getFileContent } = require('./debug');
const { Response } = jest.requireActual('node-fetch');
const mockURL = 'http://localhost:4000/sampe-article.html';
describe('Subdomain site: ', () => {
it('should return article data', async () => {
fetch.mockReturnValue(Promise.resolve(new Response(getFileContent('article.html'))));
const content = await getContent(mockURL, {
method: 'GET',
headers: {},
});
const { document } = new JSDOM(content).window;
expect(document.querySelectorAll('script').length).toEqual(1);
expect(content).toContain('<!doctype html>');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment