-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
331 lines (298 loc) · 10.9 KB
/
index.js
File metadata and controls
331 lines (298 loc) · 10.9 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/**
* Vizzly screenshot helper for Ember tests
*
* This module provides the vizzlyScreenshot function for use in Ember
* acceptance and integration tests. It captures screenshots and sends
* them to Vizzly for visual comparison.
*
* @module @vizzly-testing/ember/test-support
*
* @example
* import { module, test } from 'qunit';
* import { visit } from '@ember/test-helpers';
* import { setupApplicationTest } from 'ember-qunit';
* import { vizzlyScreenshot } from '@vizzly-testing/ember/test-support';
*
* module('Acceptance | Dashboard', function(hooks) {
* setupApplicationTest(hooks);
*
* test('renders empty state', async function(assert) {
* await visit('/dashboard');
* await vizzlyScreenshot('dashboard-empty');
* assert.dom('[data-test-empty-state]').exists();
* });
* });
*/
/**
* Custom error class for intentional visual diff failures.
* Only this error type will be re-thrown to fail tests.
*
* Note: Unlike the core SDK which auto-disables on errors, the Ember client
* returns a skipped result instead. This is intentional - Ember tests often
* run in partitions/parallel where auto-disabling would affect other tests.
*/
class VizzlyDiffError extends Error {
constructor(message) {
super(message);
this.name = 'VizzlyDiffError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this, VizzlyDiffError);
}
}
}
/**
* Detect browser type from user agent
* @returns {string} Browser type: chromium, firefox, or webkit
*/
function detectBrowser() {
let ua = navigator.userAgent;
if (ua.includes('Firefox')) return 'firefox';
if (ua.includes('Safari') && !ua.includes('Chrome')) return 'webkit';
return 'chromium';
}
/**
* Get the Ember settled function if available
* Uses only AMD require to avoid bundler issues with dynamic imports
* @returns {Function|null} The settled function or null
*/
function getSettled() {
// Use AMD require which is available in Ember's test environment
// This avoids bundler issues with dynamic imports
if (typeof window !== 'undefined' && typeof window.require === 'function') {
try {
let testHelpers = window.require('@ember/test-helpers');
if (testHelpers?.settled) {
return testHelpers.settled;
}
} catch {
// Module not found - that's fine, we'll skip settling
}
}
// Also check if it's on the global (some Ember setups do this)
if (typeof window !== 'undefined' && window.Ember?.Test?.settled) {
return window.Ember.Test.settled;
}
return null;
}
/**
* Prepare the Ember testing container for screenshots
*
* By default, Ember's #ember-testing-container is scaled to 50% and positioned
* in the bottom-right corner. This function expands it to full screen for
* clean screenshots.
*
* @param {number} [width=1280] - Desired viewport width
* @param {number} [height=720] - Desired viewport height
* @param {boolean} [fullPage=false] - Whether to capture full scrollable content
* @returns {Function} Cleanup function to restore original styles
*/
function prepareTestingContainer(width = 1280, height = 720, fullPage = false) {
let container = document.getElementById('ember-testing-container');
let testing = document.getElementById('ember-testing');
if (!container || !testing) {
return () => {}; // No-op if elements don't exist
}
// Store original styles for restoration
let originalContainerStyle = container.style.cssText;
let originalTestingStyle = testing.style.cssText;
// For fullPage, we need to measure the actual content height
let containerHeight = height;
if (fullPage) {
// Temporarily reset styles to measure true content height
testing.style.transform = 'none';
testing.style.width = `${width}px`;
testing.style.height = 'auto';
testing.style.overflow = 'visible';
// Force layout recalc and get scroll height
let scrollHeight = testing.scrollHeight;
containerHeight = Math.max(height, scrollHeight);
}
// Expand container to full screen with specified dimensions
container.style.cssText = `
position: fixed !important;
top: 0 !important;
left: 0 !important;
right: auto !important;
bottom: auto !important;
width: ${width}px !important;
height: ${containerHeight}px !important;
z-index: 99999 !important;
background: #fff !important;
border: none !important;
overflow: ${fullPage ? 'visible' : 'hidden'} !important;
`;
// Reset testing element to full size (no scaling)
testing.style.cssText = `
position: absolute !important;
top: 0 !important;
left: 0 !important;
width: 100% !important;
height: ${fullPage ? 'auto' : '100%'} !important;
min-height: ${fullPage ? `${containerHeight}px` : 'auto'} !important;
transform: none !important;
overflow: ${fullPage ? 'visible' : 'hidden'} !important;
`;
// Return cleanup function
return () => {
container.style.cssText = originalContainerStyle;
testing.style.cssText = originalTestingStyle;
};
}
/**
* Check if tests should fail on visual diffs
* Reads from VIZZLY_FAIL_ON_DIFF environment variable (injected by launcher)
* @returns {boolean}
*/
function shouldFailOnDiff() {
return window.__VIZZLY_FAIL_ON_DIFF__ === true ||
window.__VIZZLY_FAIL_ON_DIFF__ === 'true';
}
/**
* Capture a visual screenshot
*
* Takes a screenshot of the Ember app and sends it to Vizzly for visual
* comparison. By default, captures just the #ember-testing element (the app),
* not the QUnit test runner UI.
*
* Automatically:
* - Waits for Ember's settled state
* - Expands the testing container to full viewport size
* - Captures the app at the specified viewport dimensions
*
* @param {string} name - Unique name for this screenshot
* @param {Object} [options] - Screenshot options
* @param {string} [options.selector] - CSS selector to capture specific element within the app
* @param {boolean} [options.fullPage=false] - Capture full scrollable content
* @param {number} [options.width=1280] - Viewport width for the screenshot
* @param {number} [options.height=720] - Viewport height for the screenshot
* @param {string} [options.scope='app'] - What to capture: 'app' (default), 'container', or 'page'
* @param {Object} [options.properties] - Additional metadata for the screenshot
* @param {boolean} [options.failOnDiff] - Fail the test if visual diff is detected (overrides env var)
* @returns {Promise<Object>} Screenshot result from Vizzly server
*
* @example
* // Capture the app at default viewport (1280x720)
* await vizzlyScreenshot('homepage');
*
* @example
* // Capture at mobile viewport
* await vizzlyScreenshot('homepage-mobile', { width: 375, height: 667 });
*
* @example
* // Capture specific element within the app
* await vizzlyScreenshot('login-form', { selector: '[data-test-login-form]' });
*
* @example
* // Fail test if this specific screenshot has a diff
* await vizzlyScreenshot('critical-ui', { failOnDiff: true });
*/
export async function vizzlyScreenshot(name, options = {}) {
let {
selector = null,
fullPage = false,
width = 1280,
height = 720,
scope = 'app',
properties = {},
failOnDiff = null, // null means use env var, true/false overrides
} = options;
// Get screenshot URL injected by the launcher
let screenshotUrl = window.__VIZZLY_SCREENSHOT_URL__;
if (!screenshotUrl) {
console.warn(
'[vizzly] No screenshot server available. Tests must be run via Vizzly launcher. ' +
'Ensure testem.js is configured with @vizzly-testing/ember.'
);
return { skipped: true, reason: 'no-server' };
}
// Wait for Ember to settle before capturing
let settled = getSettled();
if (settled) {
await settled();
}
// Prepare testing container for screenshot (expand to full size)
let cleanup = prepareTestingContainer(width, height, fullPage);
// Force a repaint to ensure styles are applied
// eslint-disable-next-line no-unused-expressions
document.body.offsetHeight;
// Determine what selector to pass to Playwright
let captureSelector = null;
if (selector) {
// User specified a selector - capture that element
// Prefix with #ember-testing if not already scoped
captureSelector = selector.startsWith('#ember-testing')
? selector
: `#ember-testing ${selector}`;
} else if (scope === 'app') {
// Default: capture just the Ember app
captureSelector = '#ember-testing';
} else if (scope === 'container') {
// Capture the testing container
captureSelector = '#ember-testing-container';
}
// scope === 'page' means captureSelector stays null (full page)
// Build request payload
let payload = {
name,
selector: captureSelector,
fullPage,
properties: {
browser: detectBrowser(),
viewport_width: width,
viewport_height: height,
...properties,
},
};
try {
// Send screenshot request to server
let response = await fetch(`${screenshotUrl}/screenshot`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
if (!response.ok) {
let errorText = await response.text();
// Check if this is a "no server" error - gracefully skip instead of failing
// This allows tests to pass when Vizzly isn't running (like Percy behavior)
if (errorText.includes('No Vizzly server found')) {
console.warn('[vizzly] Vizzly server not running. Skipping visual screenshot.');
return { status: 'skipped', reason: 'no-server' };
}
throw new Error(`Vizzly screenshot failed: ${errorText}`);
}
let result = await response.json();
// Handle visual diff - server returns 200 with status: 'diff'
if (result.status === 'diff') {
// Determine if we should fail based on option or env var
let shouldFail = failOnDiff !== null ? failOnDiff : shouldFailOnDiff();
if (shouldFail) {
throw new VizzlyDiffError(
`Visual difference detected for '${name}' (${result.diffPercentage?.toFixed(2)}% diff). ` +
`View diff in Vizzly dashboard.`
);
}
// Log warning but don't fail
console.warn(`[vizzly] Visual difference detected for '${name}'. View diff in Vizzly dashboard.`);
}
return result;
} catch (error) {
// Only re-throw intentional diff failures - everything else should skip gracefully
// We never want to break the user's test suite due to Vizzly issues
if (error instanceof VizzlyDiffError) {
throw error;
}
// Log the error for debugging but don't fail the test
console.warn(`[vizzly] Screenshot skipped due to error: ${error.message}`);
return { status: 'skipped', reason: 'error', error: error.message };
} finally {
// Always restore original styles
cleanup();
}
}
/**
* Check if Vizzly is available in the current test environment
* @returns {boolean} True if Vizzly screenshot server is available
*/
export function isVizzlyAvailable() {
return !!window.__VIZZLY_SCREENSHOT_URL__;
}