puppeteer-plugin.test.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { expect } from 'chai';
  2. import http from 'http';
  3. import finalhandler from 'finalhandler';
  4. import serveStatic from 'serve-static';
  5. import fs from 'fs-extra';
  6. import scrape from 'website-scraper';
  7. import PuppeteerPlugin from '../lib/index.js';
  8. const directory = './test/tmp';
  9. const SERVE_WEBSITE_PORT = 4567;
  10. describe('Puppeteer plugin test', () => {
  11. let result, content, server;
  12. before('start webserver', () => server = startWebserver(SERVE_WEBSITE_PORT));
  13. after('stop webserver', () => server.close())
  14. describe('Dynamic content', () => {
  15. before('scrape website', async () => {
  16. result = await scrape({
  17. urls: [`http://localhost:${SERVE_WEBSITE_PORT}`],
  18. directory: directory,
  19. plugins: [ new PuppeteerPlugin({
  20. scrollToBottom: { timeout: 50, viewportN: 10 }
  21. }) ]
  22. });
  23. });
  24. before('get content from file', () => {
  25. content = fs.readFileSync(`${directory}/${result[0].filename}`).toString();
  26. });
  27. after('delete dir', () => fs.removeSync(directory));
  28. it('should have 1 item in result array', () => {
  29. expect(result.length).eql(1);
  30. });
  31. it('should render dymanic website', async () => {
  32. expect(content).to.contain('<div id="root">Hello world from JS!</div>');
  33. });
  34. it('should render special characters correctly', async () => {
  35. expect(content).to.contain('<div id="special-characters-test">7년 동안 한국에서 살았어요. Слава Україні!</div>');
  36. });
  37. });
  38. describe('Block navigation', () => {
  39. before('scrape website', async () => {
  40. result = await scrape({
  41. urls: [`http://localhost:${SERVE_WEBSITE_PORT}/navigation.html`],
  42. directory: directory,
  43. plugins: [
  44. new PuppeteerPlugin({
  45. launchOptions: { headless: "new" },
  46. blockNavigation: true
  47. })
  48. ]
  49. });
  50. });
  51. before('get content from file', () => {
  52. content = fs.readFileSync(`${directory}/${result[0].filename}`).toString();
  53. });
  54. after('delete dir', () => fs.removeSync(directory));
  55. it('should render content (and not be redirected)', async () => {
  56. expect(content).to.contain('<div id="root">Navigation blocked!</div>');
  57. });
  58. });
  59. });
  60. function startWebserver(port = 3000) {
  61. const serve = serveStatic('./test/mock', {'index': ['index.html']});
  62. const server = http.createServer(function onRequest (req, res) {
  63. serve(req, res, finalhandler(req, res))
  64. });
  65. return server.listen(port)
  66. }