-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-dynamic.js
More file actions
263 lines (223 loc) · 8.34 KB
/
test-dynamic.js
File metadata and controls
263 lines (223 loc) · 8.34 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
/**
* Dynamic Extension Testing on Real Amazon URLs
*
* Tests the extension on multiple real Amazon product pages
* to verify different scenarios:
* - Products with FREE Returns badge
* - Products without FREE Returns badge (paid shipping)
* - Amazon.com vs Amazon.de
* - Third-party sellers vs Amazon-sold
*/
const puppeteer = require('puppeteer');
const path = require('path');
const EXTENSION_PATH = path.join(__dirname, 'dist');
// Test URLs - Add more as needed
const TEST_CASES = [
{
name: 'Amazon.de - Coffee Machine (FREE Returns)',
url: 'https://www.amazon.de/-/en/AlloverPower-E61-Group-Head-Coffee/dp/B0BNQ66ZN1',
region: 'de',
expectedBehavior: {
hasWidget: true,
defectiveFree: true,
regularFree: true, // This product has FREE Returns badge
language: 'en'
}
},
// Add more test cases here
// {
// name: 'Amazon.de - Product WITHOUT Free Returns',
// url: 'https://www.amazon.de/dp/[PRODUCT_ID]',
// region: 'de',
// expectedBehavior: {
// hasWidget: true,
// defectiveFree: true,
// regularFree: false, // Should show €6.50-€13.00
// hasCost: true,
// language: 'de'
// }
// },
];
async function testProduct(browser, testCase) {
console.log('\n' + '='.repeat(60));
console.log(`Testing: ${testCase.name}`);
console.log(`URL: ${testCase.url}`);
console.log('='.repeat(60));
const page = await browser.newPage();
// Collect console logs
const logs = [];
page.on('console', msg => {
const text = msg.text();
logs.push(text);
if (text.includes('[Amazon Returns Extension]')) {
console.log('📝', text);
}
});
try {
console.log('🌐 Navigating to product page...');
await page.goto(testCase.url, { waitUntil: 'networkidle2', timeout: 30000 });
// Handle cookie dialog if present
try {
const acceptButton = await page.waitForSelector('button[data-action="accept"], input[name="accept"]', { timeout: 3000 });
if (acceptButton) {
console.log('🍪 Accepting cookies...');
await acceptButton.click();
await new Promise(resolve => setTimeout(resolve, 1000));
}
} catch (e) {
// No cookie dialog or already accepted
}
// Wait for extension widget or badge
console.log('⏳ Waiting for extension widget or badge...');
const widgetSelector = '.amazon-returns-ext__widget';
const badgeSelector = '.amazon-returns-ext__badge-container';
let widgetFound = false;
let badgeFound = false;
try {
await page.waitForSelector(`${widgetSelector}, ${badgeSelector}`, { timeout: 10000 });
widgetFound = !!(await page.$(widgetSelector));
badgeFound = !!(await page.$(badgeSelector));
if (widgetFound) console.log('✅ Extension widget found!');
if (badgeFound) console.log('✅ Extension badge found!');
} catch (e) {
console.log('❌ Extension widget/badge NOT found');
}
if (!widgetFound && !badgeFound && testCase.expectedBehavior.hasWidget) {
console.log('⚠️ Expected widget/badge but none found');
// Debug: Check extension logs
const extensionLogs = logs.filter(log => log.includes('[Amazon Returns Extension]'));
if (extensionLogs.length > 0) {
console.log('\n📋 Extension logs:');
extensionLogs.forEach(log => console.log(' -', log));
} else {
console.log('❌ No extension logs - content script may not be running');
}
// Take debug screenshot
const debugPath = `/tmp/debug-${Date.now()}.jpg`;
await page.screenshot({ path: debugPath, type: 'jpeg', quality: 85, fullPage: false });
console.log(`📸 Debug screenshot: ${debugPath}`);
return { success: false, testCase: testCase.name, error: 'Widget not found' };
}
// Analyze widget/badge content
const widgetText = await page.evaluate(() => {
const widget = document.querySelector('.amazon-returns-ext__widget');
const badge = document.querySelector('.amazon-returns-ext__badge-container');
const element = widget || badge;
return element ? element.innerText : null;
});
console.log('\n📦 Widget Content:');
console.log('─'.repeat(50));
console.log(widgetText);
console.log('─'.repeat(50));
// Validate expectations
const results = {
hasDefective: widgetText.includes('Defective') || widgetText.includes('Defekte'),
hasRegular: widgetText.includes('Regular') || widgetText.includes('Reguläre'),
isFree: widgetText.includes('Free') || widgetText.includes('Kostenlos'),
hasCost: widgetText.includes('€') || widgetText.includes('$'),
has14Days: widgetText.includes('14'),
has30Days: widgetText.includes('30'),
};
console.log('\n✓ Validation Results:');
console.log(` Has defective section: ${results.hasDefective ? '✅' : '❌'}`);
console.log(` Has regular section: ${results.hasRegular ? '✅' : '❌'}`);
console.log(` Shows free returns: ${results.isFree ? '✅' : '❌'}`);
console.log(` Shows cost info: ${results.hasCost ? '✅' : '❌'}`);
// Check if regular returns show paid shipping when expected
if (testCase.expectedBehavior.regularFree === false) {
const showsPaidShipping = widgetText.includes('€6.50') || widgetText.includes('€13.00');
console.log(` Shows paid shipping cost: ${showsPaidShipping ? '✅' : '❌'}`);
if (!showsPaidShipping) {
console.log('⚠️ Expected paid shipping (€6.50-€13.00) but not found');
}
}
// Take screenshot
const screenshotName = testCase.name.toLowerCase().replace(/[^a-z0-9]/g, '-');
const screenshotPath = `/tmp/test-${screenshotName}.jpg`;
await page.screenshot({
path: screenshotPath,
type: 'jpeg',
quality: 85,
fullPage: false
});
console.log(`\n📸 Screenshot: ${screenshotPath}`);
// Overall pass/fail
const passed = results.hasDefective && results.hasRegular;
console.log(`\n${passed ? '🎉 TEST PASSED' : '❌ TEST FAILED'}`);
return {
success: passed,
testCase: testCase.name,
results,
widgetText,
screenshotPath
};
} catch (error) {
console.error('❌ Test error:', error.message);
return { success: false, testCase: testCase.name, error: error.message };
} finally {
await page.close();
}
}
async function runDynamicTests() {
console.log('🚀 Starting dynamic extension tests...');
console.log(`📦 Extension path: ${EXTENSION_PATH}`);
console.log(`📋 Test cases: ${TEST_CASES.length}`);
const browser = await puppeteer.launch({
headless: false,
args: [
`--disable-extensions-except=${EXTENSION_PATH}`,
`--load-extension=${EXTENSION_PATH}`,
'--no-sandbox',
'--disable-setuid-sandbox',
],
});
const results = [];
for (const testCase of TEST_CASES) {
const result = await testProduct(browser, testCase);
results.push(result);
// Wait between tests
await new Promise(resolve => setTimeout(resolve, 2000));
}
console.log('\n' + '='.repeat(60));
console.log('📊 TEST SUMMARY');
console.log('='.repeat(60));
const passed = results.filter(r => r.success).length;
const failed = results.filter(r => !r.success).length;
console.log(`\nTotal: ${results.length}`);
console.log(`Passed: ${passed} ✅`);
console.log(`Failed: ${failed} ❌`);
console.log('\nResults:');
results.forEach((r, i) => {
const icon = r.success ? '✅' : '❌';
console.log(` ${icon} ${r.testCase}`);
if (r.error) {
console.log(` Error: ${r.error}`);
}
});
console.log('\n👀 Browser will stay open for 5 seconds...');
await new Promise(resolve => setTimeout(resolve, 5000));
await browser.close();
console.log('\n✅ All tests complete');
// Exit with error code if any tests failed
process.exit(failed > 0 ? 1 : 0);
}
// Command-line usage: yarn node test-dynamic.js [URL]
if (process.argv[2]) {
const customUrl = process.argv[2];
console.log('🔍 Testing custom URL:', customUrl);
TEST_CASES.length = 0; // Clear default tests
TEST_CASES.push({
name: 'Custom URL Test',
url: customUrl,
region: customUrl.includes('.de') ? 'de' : 'com',
expectedBehavior: {
hasWidget: true,
defectiveFree: true,
language: 'auto'
}
});
}
runDynamicTests().catch(error => {
console.error('Fatal error:', error);
process.exit(1);
});