-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmountSvelteComponent.js
More file actions
189 lines (154 loc) · 5.14 KB
/
Copy pathmountSvelteComponent.js
File metadata and controls
189 lines (154 loc) · 5.14 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
const AssertionError = require('assertion-error');
class NightwatchMountError extends AssertionError {
constructor(message) {
super(message);
this.name = 'NightwatchMountError';
}
}
module.exports = class Command {
get pluginSettings() {
return this.client.settings['@nightwatch/svelte'] || {};
}
getError(message) {
const err = new NightwatchMountError(message);
err.showTrace = false;
err.help = [
'run nightwatch with --devtools and --debug flags (Chrome only)',
'investigate the error in the browser console'
];
return err;
}
async mountComponent(componentName, opts, isRetry = false) {
await this.api.execute(function (innerHTML) {
function onReady(fn) {
if (document.readyState === 'complete' || document.readyState === 'interactive') {setTimeout(fn)} else {document.addEventListener('DOMContentLoaded', fn)}
}
onReady(function() {
var scriptTag = Object.assign(document.createElement('script'), {
type: 'module',
innerHTML
});
document.body.appendChild(scriptTag);
});
}, [Command._buildScript(componentName, opts)], async (result) => {
if (result && (result.error instanceof Error) && !isRetry) {
return this.mountComponent(componentName, opts, true);
}
return result;
});
}
async command(componentName, opts = {}, cb = function() {}) {
const {
hooksRetryTimeout = 10000,
hooksRetryInterval = 150,
playFnTimeout = 20000,
playFnRetryInterval = 100
} = this.pluginSettings;
await this.api.launchComponentRenderer();
await this.mountComponent(componentName, opts);
await this.api
.waitUntil(async () => {
if (this.client.argv.debug) {
return true;
}
const result = await this.api.execute(function() {
return !!window['@@component_class'];
});
return !!result;
}, hooksRetryTimeout, hooksRetryInterval, this.getError(`time out reached (${hooksRetryTimeout}ms) while waiting for component to mount.`))
// run the play() function
.execute(function(innerHTML) {
var scriptTag = Object.assign(document.createElement('script'), {
type: 'module',
innerHTML
});
document.body.appendChild(scriptTag);
}, [`
const Component = window['@@component_class'];
if (Component && (typeof Component.play == 'function')) {
try {
window['@@playfn_result'] = await Component.play({
component: window['@@component_element']
}) || {};
} catch (err) {
console.error('Error while executing .play() function:', err);
window.__$$PlayFnError = err;
}
}
window.__$$PlayFnDone = true;
`]);
if (this.client.argv.debug) {
await this.api.debug();
} else if (this.client.argv.preview) {
await this.api.pause();
}
const result = await this.api.execute(function() {
return document.querySelectorAll('#app')[0].firstElementChild;
}, []);
if (!result) {
const err = this.getError('Could not mount the component.');
return err;
}
const componentInstance = this.api.createElement(result, {
isComponent: true,
type: 'svelte'
});
cb(componentInstance);
return componentInstance;
}
static _getMockContent(mocks = {}) {
const definitions = Object.keys(mocks);
let mockContent = '';
let mockFetch = false;
const mockFetchContent = `
function mockApiResponse(body) {
return new window.Response(JSON.stringify(body), {
status: 200,
headers: {
'Content-type': 'application/json'
}
});
}
const stubedFetch = sinon.stub(window, 'fetch');
`;
let mockFetchItemsContent = '';
if (definitions.length > 0) {
mockContent = 'import sinon from \'/node_modules/sinon/pkg/sinon-esm.js\';';
mockFetchItemsContent = definitions.reduce((prev, mockUrl) => {
const {body, type = 'fetch'} = mocks[mockUrl];
if (type === 'fetch') {
mockFetch = true;
}
prev += `
stubedFetch.withArgs('${mockUrl}').returns(sinon.promise(function (resolve, reject) {
resolve(mockApiResponse(${JSON.stringify(body)}));
}));
`;
return prev;
}, '');
}
if (mockFetch) {
mockContent += mockFetchContent;
mockContent += mockFetchItemsContent;
}
return mockContent;
}
static _buildScript(componentName, opts = {}) {
return `
import Component from '${componentName}'
${Command._getMockContent(opts.mocks)}
const element = new (Component || Component.default)({
target: document.getElementById('app'),
props: ${JSON.stringify(opts.props || {})},
context: ${opts.context},
anchor: ${opts.anchor || null},
intro: ${opts.intro || false}
});
window['@@component_element'] = element;
window['@@component_class'] = Component;
window['@@playfn_result'] = null;
window.__$$PlayFnError = null;
window.__$$PlayFnDone = false;
`;
}
};