Skip to content

Commit

Permalink
fixed test for discovery
Browse files Browse the repository at this point in the history
  • Loading branch information
amandeepsingh333 committed Jan 10, 2025
1 parent 3ff670d commit 288517d
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 72 deletions.
2 changes: 1 addition & 1 deletion packages/core/src/browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ export class Browser extends EventEmitter {
}
}

async spawn(timeout = 80000) {
async spawn(timeout = 30000) {
// spawn the browser process detached in its own group and session
this.process = spawn(this.executable, this.args, {
detached: process.platform !== 'win32'
Expand Down
11 changes: 6 additions & 5 deletions packages/core/src/install.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,11 +177,12 @@ export function chromium({

// default chromium revisions corresponds to v123.0.6312.58
chromium.revisions = {
linux: '1262506',
win64: '1262500',
win32: '1262500',
darwin: '1262506',
darwinArm: '1262509'
linux: '1368524',
win64: '1368503',
win32: '1368516',
darwin: '1368518',
darwinArm: '1368521'
};

// export the namespace by default
export * as default from './install.js';
16 changes: 14 additions & 2 deletions packages/core/src/network.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class RequestLifeCycleHandler {
this.resolveResponseReceived = null;
this.requestWillBeSent = new Promise((resolve) => (this.resolveRequestWillBeSent = resolve));
this.responseReceived = new Promise((resolve) => (this.resolveResponseReceived = resolve));
this.isWorker = false;
}
}
// The Interceptor class creates common handlers for dealing with intercepting asset requests
Expand Down Expand Up @@ -216,10 +217,16 @@ export class Network {
// otherwise set it to be pending until it is paused.
_handleRequestWillBeSent = async event => {
let { requestId, request, type } = event;

// do not handle data urls
if (request.url.startsWith('data:')) return;

const isWorker = type === 'Worker' || request.url.endsWith('.js');
// Mark in the lifecycle handler if this is a worker request
this.#requestsLifeCycleHandler.get(requestId).isWorker = isWorker;
if (isWorker) {
this.log.debug(`Auto-resolving responseReceived for worker request: ${request.url}`);
this.#requestsLifeCycleHandler.get(requestId).resolveResponseReceived();
}
// Browsers handle URL encoding leniently.
// This code checks for issues such as `%` and leading spaces and warns the user accordingly.
decodeAndEncodeURLWithLogging(request.url, this.log, {
Expand Down Expand Up @@ -302,7 +309,12 @@ export class Network {
_handleLoadingFinished = async (session, event) => {
let { requestId } = event;
// wait for upto 2 seconds or check if response has been sent
await this.#requestsLifeCycleHandler.get(requestId).responseReceived;
const handler = this.#requestsLifeCycleHandler.get(requestId);

// For worker requests, we don't need to wait for responseReceived
if (!handler.isWorker) {
await handler.responseReceived;
}
let request = this.#requests.get(requestId);
/* istanbul ignore if: race condition paranioa */
if (!request) return;
Expand Down
73 changes: 26 additions & 47 deletions packages/core/test/discovery.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -586,7 +586,6 @@ describe('Discovery', () => {

expect(server.requests.map(r => r[0]).filter(req => req !== '/favicon.ico'))
.toEqual(['/', '/script.js', '/test.json']);


expect(captured[0]).not.toEqual(jasmine.arrayContaining([
jasmine.objectContaining({
Expand Down Expand Up @@ -807,12 +806,8 @@ describe('Discovery', () => {

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) {
self.postMessage("error");
}
let response = await fetch(new Request(data));
self.postMessage("done");
});
`]);

Expand All @@ -827,28 +822,23 @@ describe('Discovery', () => {
worker.addEventListener("message", ({ data }) => {
document.body.classList.add(data);
console.log('Worker message received:', data);
});
setTimeout(() => {
console.log('Sending message to worker');
worker.postMessage("http://localhost:8000/img.gif");
}, 100);
</script>
</body>
</html>
`]);

server.reply('/img.gif', () => [200, 'image/gif', 'GIF89a...']);

await percy.snapshot({
name: 'worker snapshot',
url: 'http://localhost:8000',
waitForSelector: '.done',
enableJavaScript: true,
waitForSelector: '.done',
waitForTimeout: 1000
});

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

Expand All @@ -861,10 +851,6 @@ describe('Discovery', () => {
})
])
);
if (!captured.length) {
console.log('No resources captured');
console.log('Server requests:', server.requests);
}
});

it('does not error on cancelled requests', async () => {
Expand Down Expand Up @@ -1765,7 +1751,7 @@ describe('Discovery', () => {
await percy.snapshot({
name: 'auth snapshot',
url: 'http://localhost:8000/auth',
domSnapshot: authDOM,
domSnapshot: authDOM
});

await percy.idle();
Expand All @@ -1780,27 +1766,24 @@ 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' },
networkIdleTimeout: 5000
},
});

await percy.idle();
console.log('auth credentials');
console.log(captured[0]);

expect(captured[0]).not.toEqual(jasmine.arrayContaining([
jasmine.objectContaining({
attributes: jasmine.objectContaining({
'resource-url': 'http://localhost:8000/auth/img.gif'
})
await percy.snapshot({
name: 'auth snapshot',
url: 'http://localhost:8000/auth',
domSnapshot: authDOM,
discovery: {
authorization: { username: 'invalid' },
networkIdleTimeout: 5000
}
});

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

Expand Down Expand Up @@ -2216,20 +2199,19 @@ describe('Discovery', () => {
discovery: {
launchOptions: {
args: ['--remote-debugging-port=null'],
},
},
timeout: 5000
}
}
})
).toBeRejectedWithError(/Failed to launch browser/);

// Access the last request from the API logs
const lastRequestIndex = api.requests['/suggestions/from_logs'].length - 1;
const lastLogMessage = api.requests['/suggestions/from_logs'][lastRequestIndex].body.data.logs[0].message;

// Validate the log contains the correct error message
expect(lastLogMessage.includes('Failed to launch browser')).toEqual(true);
});



it('should fail to launch after the timeout', async () => {
await expectAsync(Percy.start({
Expand Down Expand Up @@ -2531,9 +2513,6 @@ describe('Discovery', () => {
await percy.idle();

let paths = server.requests.map(r => r[0]);
console.log("original requestss");
console.log(paths);
console.log(captured);
expect(paths).toContain('/img.gif');
expect(captured).toContain(jasmine.arrayContaining([
jasmine.objectContaining({
Expand Down
27 changes: 10 additions & 17 deletions packages/core/test/snapshot.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1230,7 +1230,7 @@ describe('Snapshot', () => {
await percy.idle();

let dom = i => Buffer.from((
api.requests['/builds/123/resources'][i*3]
api.requests['/builds/123/resources'][i * 3]
.body.data.attributes['base64-content']
), 'base64').toString();
console.log('DOM 0:', dom(0));
Expand All @@ -1242,7 +1242,7 @@ describe('Snapshot', () => {
expect(dom(2)).toMatch('<p class="eval-1 eval-2 eval-3">Test</p>');
expect(dom(3)).toMatch('<p class="eval-1 eval-2 eval-3 eval-4">Test</p>');
});

it('can successfully snapshot a page after executing page navigation', async () => {
testDOM += '<a href="/foo">Foo</a>';

Expand Down Expand Up @@ -1296,27 +1296,24 @@ describe('Snapshot', () => {
execute() {
let $p = document.querySelector('p');
if ($p) $p.id = 'framed';

let $f = document.querySelector('iframe');
if ($f) $f.src = '/foo';
}
});

expect(logger.stderr).toEqual([]);
expect(logger.stdout).toContain(
'[percy] Snapshot taken: framed snapshot'
);

await percy.idle();

const snapshotContent = Buffer.from((
api.requests['/builds/123/resources'][0]
.body.data.attributes['base64-content']
), 'base64').toString();

// Log the full snapshot content for inspection
console.log('Snapshot Content:', snapshotContent);


// More flexible matching
expect(snapshotContent).toMatch(/<iframe/);
// Update the regex to match the HTML-encoded <p> tag
Expand Down Expand Up @@ -1384,37 +1381,33 @@ describe('Snapshot', () => {
const p1 = document.createElement('p');
p1.textContent = 'beforeResize - 400';
document.body.appendChild(p1);

// Simulate a resize event
await new Promise(resolve => setTimeout(resolve, 100)); // Allow time for changes
const p2 = document.createElement('p');
p2.textContent = 'afterResize - 800';
document.body.appendChild(p2);

// Simulate another resize event
await new Promise(resolve => setTimeout(resolve, 100)); // Allow time for changes
const p3 = document.createElement('p');
p3.textContent = 'beforeResize - 800';
document.body.appendChild(p3);

// Simulate a final resize event
await new Promise(resolve => setTimeout(resolve, 100)); // Allow time for changes
const p4 = document.createElement('p');
p4.textContent = 'afterResize - 1200';
document.body.appendChild(p4);
}
});

await percy.idle();

const snapshotContent = Buffer.from((
api.requests['/builds/123/resources'][0]
.body.data.attributes['base64-content']
), 'base64').toString();

// Log the full snapshot content for inspection
console.log('Snapshot Content:', snapshotContent);

// More flexible matching
expect(snapshotContent).toMatch(/<p>beforeResize - 400<\/p>/);
expect(snapshotContent).toMatch(/<p>afterResize - 800<\/p>/);
Expand Down

0 comments on commit 288517d

Please sign in to comment.