forked from bahmutov/cypress-watch-and-reload
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugins.js
More file actions
68 lines (58 loc) · 2.12 KB
/
plugins.js
File metadata and controls
68 lines (58 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const WebSocket = require('ws')
const chokidar = require('chokidar')
const { join } = require('path')
module.exports = (config) => {
// https://github.com/websockets/ws#simple-server
// create socket even if not watching files to avoid
// tripping up client trying to connect
const wss = new WebSocket.Server({ port: 8765 })
let client // future Cypress client
const cypressJson = config.configFile
? require(config.configFile)
: require(join(process.cwd(), 'cypress.json'))
const options = cypressJson['cypress-watch-and-reload']
let watchPathOrPaths = options && options.watch
// utils to check type of options.watch
const isWatchPathString = typeof watchPathOrPaths === 'string'
const isWatchPathArray =
Array.isArray(watchPathOrPaths) && watchPathOrPaths.length
const isWatchPathStringOrArray = isWatchPathString || isWatchPathArray
if (isWatchPathStringOrArray) {
if (isWatchPathArray) {
watchPathOrPaths = options.watch.map((path) => `"${path}"`).join(', ')
} else {
watchPathOrPaths = `"${watchPathOrPaths}"`
}
console.log(
'cypress-watch-and-reload: maybe will watch %s',
watchPathOrPaths,
)
let watcher = null
wss.on('connection', function connection(ws) {
console.log('cypress-watch-and-reload: new socket connection 🎉')
client = ws
console.log('cypress-watch-and-reload: starting to watch files')
if (watcher) {
watcher.close()
}
watcher = chokidar.watch(options.watch).on('change', (path, event) => {
console.log('cypress-watch-and-reload: file %s has changed', path)
if (client) {
const text = JSON.stringify({
command: 'reload',
filename: path,
})
client.send(text)
}
})
})
} else {
console.log(
'nothing to watch. Use cypress.json to set "cypress-watch-and-reload" object',
)
console.log('see https://github.com/bahmutov/cypress-watch-and-reload#use')
}
// set an internal variable to let the browser-side code know
config.env.cypressWatchAndReloadPluginInitialized = true
return config
}