initDOM.js 1.75 KB
Newer Older
1
2
3
4
const fs = require('fs')
const http = require('http')
const jsdom = require('jsdom')
const path = require('path')
5
const { expect } = require('chai')
6
7
8
9
10
11
12
13
14
15
16
17

let getMarkup
let resourceLoader

if (process.env.E2E_FILE) {
  const file = path.isAbsolute(process.env.E2E_FILE)
    ? process.env.E2E_FILE
    : path.join(process.cwd(), process.env.E2E_FILE)

  const markup = fs.readFileSync(file, 'utf8')
  getMarkup = () => markup

18
19
  const pathPrefix = process.env.PUBLIC_URL.replace(/^https?:\/\/[^\/]+\/?/, '')

20
21
  resourceLoader = (resource, callback) => callback(
    null,
22
    fs.readFileSync(path.join(path.dirname(file), resource.url.pathname.replace(pathPrefix, '')), 'utf8')
23
24
25
26
27
28
29
30
31
32
  )
} else if (process.env.E2E_URL) {
  getMarkup = () => new Promise(resolve => {
    http.get(process.env.E2E_URL, (res) => {
      let rawData = ''
      res.on('data', chunk => rawData += chunk)
      res.on('end', () => resolve(rawData))
    })
  })

Fabrizio Castellarin's avatar
Fabrizio Castellarin committed
33
  resourceLoader = (resource, callback) => resource.defaultFetch(callback)
34
35
} else {
  it.only('can run jsdom (at least one of "E2E_FILE" or "E2E_URL" environment variables must be provided)', () => {
36
    expect(new Error('This isn\'t the error you are looking for.')).to.be.undefined()
37
38
39
40
41
  })
}

export default feature => new Promise(async resolve => {
  const markup = await getMarkup()
42
  const host = process.env.E2E_URL || 'http://www.example.org/spa:3000'
43
  const doc = jsdom.jsdom(markup, {
Fabrizio Castellarin's avatar
Fabrizio Castellarin committed
44
45
46
    features: {
      FetchExternalResources: ['script', 'css'],
      ProcessExternalResources: ['script'],
47
    },
Fabrizio Castellarin's avatar
Fabrizio Castellarin committed
48
49
    created: (_, win) => win.addEventListener('ReactFeatureDidMount', () => resolve(doc), true),
    deferClose: true,
50
51
52
53
54
    resourceLoader,
    url: `${host}#${feature}`,
    virtualConsole: jsdom.createVirtualConsole().sendTo(console),
  })

Fabrizio Castellarin's avatar
Fabrizio Castellarin committed
55
  doc.close()
56
})