Skip to content

Commit

Permalink
testing errors
Browse files Browse the repository at this point in the history
  • Loading branch information
amandeepsingh333 committed Dec 19, 2024
1 parent 9c81102 commit 7dcfe32
Show file tree
Hide file tree
Showing 2 changed files with 237 additions and 169 deletions.
261 changes: 172 additions & 89 deletions packages/core/test/discovery.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -791,65 +791,80 @@ describe('Discovery', () => {
});
});

it('captures requests from workers', async () => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;

// Adjust timing for Network events
spyOn(percy.browser, '_handleMessage').and.callFake(function(data) {
let { method } = JSON.parse(data);

if (method === 'Network.requestWillBeSent') {
setTimeout(this._handleMessage.and.originalFn.bind(this), 10, data); // Reduce delay
} else {
this._handleMessage.and.originalFn.call(this, data);
}
});

server.reply('/worker.js', () => [200, 'text/javascript', dedent`
self.addEventListener("message", async ({ data }) => {
let response = await fetch(new Request(data));
self.postMessage("done");
it('captures requests from workers', async () => {

Check failure on line 794 in packages/core/test/discovery.test.js

View workflow job for this annotation

GitHub Actions / Lint

Expected indentation of 2 spaces but found 4
jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;

Check failure on line 795 in packages/core/test/discovery.test.js

View workflow job for this annotation

GitHub Actions / Lint

Expected indentation of 4 spaces but found 6

Check failure on line 796 in packages/core/test/discovery.test.js

View workflow job for this annotation

GitHub Actions / Lint

Trailing spaces not allowed
// Adjust timing for Network events

Check failure on line 797 in packages/core/test/discovery.test.js

View workflow job for this annotation

GitHub Actions / Lint

Expected indentation of 4 spaces but found 6
spyOn(percy.browser, '_handleMessage').and.callFake(function(data) {

Check failure on line 798 in packages/core/test/discovery.test.js

View workflow job for this annotation

GitHub Actions / Lint

Expected indentation of 4 spaces but found 6
let { method } = JSON.parse(data);

Check failure on line 799 in packages/core/test/discovery.test.js

View workflow job for this annotation

GitHub Actions / Lint

Expected indentation of 6 spaces but found 8

Check failure on line 800 in packages/core/test/discovery.test.js

View workflow job for this annotation

GitHub Actions / Lint

Trailing spaces not allowed
if (method === 'Network.requestWillBeSent') {

Check failure on line 801 in packages/core/test/discovery.test.js

View workflow job for this annotation

GitHub Actions / Lint

Expected indentation of 6 spaces but found 8
setTimeout(this._handleMessage.and.originalFn.bind(this), 10, data); // Reduce delay
} else {
this._handleMessage.and.originalFn.call(this, data);
}
});
`]);

server.reply('/', () => [200, 'text/html', dedent`
<!DOCTYPE html><html><head></head><body><script>
let worker = new Worker("/worker.js");
worker.addEventListener("message", ({ data }) => document.body.classList.add(data));
setTimeout(() => worker.postMessage("http://localhost:8000/img.gif"), 100);
</script></body></html>
`]);

// Capture snapshot and wait for worker to finish
await percy.snapshot({
name: 'worker snapshot',
url: 'http://localhost:8000',
waitForSelector: '.done',
enableJavaScript: true,
networkIdleTimeout: 2000
});

// Wait explicitly for the 'done' class
await page.waitForFunction(() => document.body.classList.contains('done'), { timeout: 60000 });

await percy.idle();

// Log requests for debugging
console.log('Requests captured:', server.requests.map(r => r[0]));
console.log('Captured resources:', captured);

// Verify the requests
let paths = server.requests.map(r => r[0]);
expect(paths).toContain('/img.gif');

// Verify the captured resource
expect(captured).toContain(jasmine.arrayContaining([
jasmine.objectContaining({
attributes: jasmine.objectContaining({
'resource-url': 'http://localhost:8000/img.gif'

// Add reply for the image request
server.reply('/img.gif', () => [200, 'image/gif', 'GIF89a...']); // Mock image response

server.reply('/worker.js', () => [200, 'text/javascript', dedent`
self.addEventListener("message", async ({ data }) => {
try {
let response = await fetch(new Request(data));
self.postMessage("done");
} catch (error) {
console.error('Worker fetch error:', error);
self.postMessage("error");
}
});
`]);

server.reply('/', () => [200, 'text/html', dedent`
<!DOCTYPE html><html><head></head><body><script>
let worker = new Worker("/worker.js");
worker.addEventListener("message", ({ data }) => {
document.body.classList.add(data);
console.log('Worker message received:', data);
});
worker.addEventListener("error", (error) => {
console.error('Worker error:', error);
});
setTimeout(() => worker.postMessage("http://localhost:8000/img.gif"), 100);
</script></body></html>
`]);

// Capture snapshot and wait for worker to finish
const snapshotPromise = percy.snapshot({
name: 'worker snapshot',
url: 'http://localhost:8000',
waitForSelector: '.done',
enableJavaScript: true,
networkIdleTimeout: 2000
});

// Wait for snapshot to complete
await snapshotPromise;

// Wait for Percy to finish processing
await percy.idle();

// Log requests for debugging
console.log('Requests captured:', server.requests.map(r => r[0]));
console.log('Captured resources:', captured);

// Verify the requests
let paths = server.requests.map(r => r[0]);
expect(paths).toContain('/img.gif');

// Verify the captured resource
expect(captured).toContain(jasmine.arrayContaining([
jasmine.objectContaining({
attributes: jasmine.objectContaining({
'resource-url': 'http://localhost:8000/img.gif'
})
})
})
]));
]));
});


Expand Down Expand Up @@ -1766,24 +1781,53 @@ describe('Discovery', () => {
});

it('does not capture with invalid auth credentials', async () => {
await percy.snapshot({
name: 'auth snapshot',
url: 'http://localhost:8000/auth',
domSnapshot: authDOM,
discovery: {
authorization: { username: 'invalid' }
// Mock endpoints
server.reply('/auth', () => [200, 'text/html', authDOM]);
server.reply('/auth/img.gif', (req) => {
// Reject invalid credentials
if (req.headers.authorization === 'invalid') {
return [401, 'text/plain', 'Unauthorized'];
}
return [200, 'image/gif', 'GIF89a...'];
});

await percy.idle();

expect(captured[0]).not.toEqual(jasmine.arrayContaining([
jasmine.objectContaining({
attributes: jasmine.objectContaining({
'resource-url': 'http://localhost:8000/auth/img.gif'

try {
// Take snapshot with invalid auth credentials
await percy.snapshot({
name: 'auth snapshot',
url: 'http://localhost:8000/auth',
domSnapshot: authDOM,
discovery: {
authorization: { username: 'invalid' },
// Add additional discovery options for stability
networkIdleTimeout: 5000,
requestTimeout: 30000
},
// Maintain consistent width with Percy config
widths: [1000]
});

// Wait for Percy to finish processing
await percy.idle();

// Original assertion
expect(captured[0]).not.toEqual(jasmine.arrayContaining([
jasmine.objectContaining({
attributes: jasmine.objectContaining({
'resource-url': 'http://localhost:8000/auth/img.gif'
})
})
})
]));
]));

} catch (error) {
// Log error details if in debug mode
if (process.env.DEBUG) {
console.error('Test error:', error);
console.error('Server requests at time of error:', server.requests);
console.error('Captured resources at time of error:', captured);
}
throw error;
}
});
});

Expand Down Expand Up @@ -2193,25 +2237,35 @@ describe('Discovery', () => {

it('should fail to launch if the devtools address is not logged', async () => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
await expectAsync(Percy.start({
token: 'PERCY_TOKEN',
snapshot: { widths: [1000] },
discovery: {
launchOptions: {
args: ['--remote-debugging-port=null']

// Wrap the test in a try-catch to log additional debug information
try {
// Test the behavior of Percy when the browser fails to launch
await expectAsync(Percy.start({
token: 'PERCY_TOKEN',
snapshot: { widths: [1000] },
discovery: {
launchOptions: {
args: ['--remote-debugging-port=null']
}
}
}
})).toBeRejectedWithError(
/Failed to launch browser/
);

// We are checking here like this, to avoid flaky test as
// the error message contains some number
// eg: `Failed to launch browser. \n[0619/152313.736334:ERROR:command_line_handler.cc(67)`
let lastRequest = api.requests['/suggestions/from_logs'].length - 1;
expect(api.requests['/suggestions/from_logs'][lastRequest].body.data.logs[0].message.includes('Failed to launch browser'))
.toEqual(true);
})).toBeRejectedWithError(/Failed to launch browser/);

// Ensure the error log contains the expected message
let lastRequestIndex = api.requests['/suggestions/from_logs'].length - 1;
let logMessage = api.requests['/suggestions/from_logs'][lastRequestIndex]?.body?.data?.logs[0]?.message;

// Assert the log message includes the "Failed to launch browser" text
expect(logMessage).toBeDefined();
expect(logMessage).toContain('Failed to launch browser');
} catch (error) {
// Debug additional information if the test fails
console.error('Test failed with error:', error);
console.error('Captured API requests:', api.requests['/suggestions/from_logs']);
throw error; // Rethrow the error to mark the test as failed
}
});


it('should fail to launch after the timeout', async () => {
await expectAsync(Percy.start({
Expand Down Expand Up @@ -2463,6 +2517,35 @@ describe('Discovery', () => {

describe('Service Worker =>', () => {
it('captures original request', async () => {
const percy = await Percy.start({
token: 'PERCY_TOKEN',
snapshot: {
widths: [1000],
networkIdleTimeout: 5000
},
discovery: {
launchOptions: {
executable: './404',
args: [
'--no-sandbox',
'--unknown-flag',
'--disable-dev-shm-usage',
'--disable-gpu',
'--disable-web-security',
'--disable-features=IsolateOrigins,site-per-process'
],
// Chrome 131 specific options
ignoreDefaultArgs: false,
headless: 'new', // Use new headless mode
timeout: 60000
},
// Add additional discovery options for Chrome 131
networkIdleTimeout: 5000,

requestTimeout: 60000
}
});

server.reply('/sw.js', () => [200, 'text/javascript', dedent`
const fetchUpstream = async(request) => {
return await fetch(request.clone());
Expand Down
Loading

0 comments on commit 7dcfe32

Please sign in to comment.