Last active
December 26, 2020 06:37
-
-
Save vanduc1102/8f9d4e8439e34ef5b95bfbe1c743423a to your computer and use it in GitHub Desktop.
Jest testing DOM in Node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const path = require('path'); | |
function getFileContent(filePath) { | |
return fs.createReadStream(path.resolve(__dirname, filePath)); | |
} | |
module.exports = { | |
getFileContent | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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