Skip to content

Commit da292f1

Browse files
committed
chore: selectively re-add tests
1 parent 35f07be commit da292f1

3 files changed

Lines changed: 229 additions & 1 deletion

File tree

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
import assert from 'node:assert/strict';
2+
import { beforeEach, describe, it, mock } from 'node:test';
3+
4+
import { act, render } from '@testing-library/react';
5+
6+
mock.module('next/navigation', {
7+
namedExports: { usePathname: () => '/en/about' },
8+
});
9+
10+
const { default: useCarbonAd } = await import('#site/hooks/useCarbonAd');
11+
12+
const ad = {
13+
company: 'Company',
14+
statlink: 'https://srv.buysellads.com/ads/click/x/1',
15+
statview: 'https://srv.buysellads.com/ads/view/x/1',
16+
};
17+
18+
let requests;
19+
let observers;
20+
let beacons;
21+
22+
class FakeIntersectionObserver {
23+
constructor(callback) {
24+
this.callback = callback;
25+
observers.push(this);
26+
}
27+
28+
observe() {}
29+
30+
disconnect() {
31+
this.disconnected = true;
32+
}
33+
}
34+
35+
const intersect = ratio =>
36+
act(() => {
37+
for (const observer of observers.filter(o => !o.disconnected)) {
38+
observer.callback([{ intersectionRatio: ratio }]);
39+
}
40+
});
41+
42+
// Lets pending fetch promises and their React state updates settle
43+
const flush = () => act(() => new Promise(resolve => setTimeout(resolve, 0)));
44+
45+
const Probe = () => {
46+
const { ad, ref } = useCarbonAd('CWBI6KJY');
47+
48+
return ad ? <div ref={ref}>{ad.company}</div> : null;
49+
};
50+
51+
const renderAd = async t => {
52+
render(<Probe />);
53+
await flush();
54+
55+
t.mock.timers.enable({ apis: ['setTimeout'] });
56+
};
57+
58+
beforeEach(() => {
59+
requests = [];
60+
observers = [];
61+
beacons = [];
62+
63+
mock.method(globalThis, 'fetch', async url => {
64+
requests.push(new URL(url));
65+
66+
return { ok: true, json: async () => ({ ads: [ad] }) };
67+
});
68+
69+
window.matchMedia = () => ({
70+
matches: true,
71+
addEventListener() {},
72+
removeEventListener() {},
73+
});
74+
75+
globalThis.IntersectionObserver = FakeIntersectionObserver;
76+
77+
globalThis.Image = class {
78+
set src(value) {
79+
beacons.push(value);
80+
}
81+
};
82+
});
83+
84+
describe('useCarbonAd', () => {
85+
it('does not count impressions outside production', async () => {
86+
render(<Probe />);
87+
await flush();
88+
89+
assert.equal(requests.length, 1);
90+
assert.equal(requests[0].searchParams.get('ignore'), 'yes');
91+
});
92+
93+
it('sends the view beacon after the ad was at least 50% visible for one second', async t => {
94+
await renderAd(t);
95+
96+
intersect(0.5);
97+
t.mock.timers.tick(999);
98+
99+
assert.deepEqual(beacons, []);
100+
101+
t.mock.timers.tick(1);
102+
103+
assert.deepEqual(beacons, [ad.statview]);
104+
});
105+
106+
it('does not send the view beacon when the ad stops being visible within one second', async t => {
107+
await renderAd(t);
108+
109+
intersect(1);
110+
t.mock.timers.tick(500);
111+
intersect(0.4);
112+
t.mock.timers.tick(5000);
113+
114+
assert.deepEqual(beacons, []);
115+
});
116+
117+
it('sends the view beacon only once per ad', async t => {
118+
await renderAd(t);
119+
120+
for (let i = 0; i < 3; i++) {
121+
intersect(1);
122+
t.mock.timers.tick(1000);
123+
}
124+
125+
assert.equal(beacons.length, 1);
126+
});
127+
});
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import { test, expect, type Page } from '@playwright/test';
2+
3+
const zones = { top: 'CWBI6KJY', sidebar: 'CWBI6KJU' };
4+
5+
const createAd = (id: string) => ({
6+
company: `Company ${id}`,
7+
description: `Description ${id}`,
8+
callToAction: 'Learn more',
9+
image: 'https://cdn4.buysellads.net/test.png',
10+
largeImage: 'https://cdn4.buysellads.net/test.png',
11+
backgroundColor: '#ffffff',
12+
textColor: '#000000',
13+
ctaBackgroundColor: '#000000',
14+
ctaTextColor: '#ffffff',
15+
statlink: `https://srv.buysellads.com/ads/click/x/${id}`,
16+
statview: `https://srv.buysellads.com/ads/view/x/${id}`,
17+
ad_via_link: 'https://www.carbonads.net/',
18+
});
19+
20+
/**
21+
* Serves fixtures instead of contacting Carbon Ads, and records every ad request
22+
*/
23+
const mockAds = async (page: Page) => {
24+
const requests: Array<string> = [];
25+
26+
await page.route('https://srv.carbonads.net/**', route => {
27+
const zone = new URL(route.request().url()).pathname;
28+
requests.push(zone);
29+
30+
return route.fulfill({
31+
json: { ads: [createAd(String(requests.length))] },
32+
headers: { 'access-control-allow-origin': '*' },
33+
});
34+
});
35+
36+
await page.route('https://srv.buysellads.com/**', route =>
37+
route.fulfill({ body: '' })
38+
);
39+
40+
await page.route('https://cdn4.buysellads.net/**', route =>
41+
route.fulfill({ body: '' })
42+
);
43+
44+
return requests;
45+
};
46+
47+
const adLinks = (page: Page) =>
48+
page.locator('a[href^="https://srv.buysellads.com/ads/click/"]');
49+
50+
test.describe('Carbon Ads', () => {
51+
test.use({ viewport: { width: 1440, height: 900 } });
52+
53+
test('should never show or request ads on the homepage', async ({ page }) => {
54+
const requests = await mockAds(page);
55+
56+
await page.goto('/en');
57+
await page.waitForLoadState('networkidle');
58+
59+
expect(requests).toEqual([]);
60+
await expect(adLinks(page)).toHaveCount(0);
61+
});
62+
63+
test('should request each format once per page view', async ({ page }) => {
64+
const requests = await mockAds(page);
65+
66+
await page.goto('/en/about');
67+
await expect(adLinks(page)).toHaveCount(2);
68+
69+
expect(requests.sort()).toEqual([
70+
`/ads/${zones.sidebar}.json`,
71+
`/ads/${zones.top}.json`,
72+
]);
73+
74+
// Client-side navigation starts a new page view (Top Bar only)
75+
await page.locator('nav a[href="/en/blog"]').first().click();
76+
await page.waitForURL('**/en/blog');
77+
await expect(adLinks(page)).toHaveCount(1);
78+
await expect(page.getByAltText('Company 3')).toBeVisible();
79+
80+
expect(requests).toHaveLength(3);
81+
82+
// Navigating to the homepage removes the ads, without new requests
83+
await page.locator('nav a[href="/en"]').first().click();
84+
await page.waitForURL(/\/en$/);
85+
await page.waitForLoadState('networkidle');
86+
87+
await expect(adLinks(page)).toHaveCount(0);
88+
expect(requests).toHaveLength(3);
89+
});
90+
91+
test('should not request the Sidebar on narrow screens', async ({ page }) => {
92+
await page.setViewportSize({ width: 375, height: 800 });
93+
94+
const requests = await mockAds(page);
95+
96+
await page.goto('/en/about');
97+
await expect(adLinks(page)).toHaveCount(1);
98+
99+
expect(requests).toEqual([`/ads/${zones.top}.json`]);
100+
});
101+
});

‎docs/carbon-ads.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,4 @@ There is no Content Security Policy on the Website at the moment. If one is adde
5555

5656
## Testing
5757

58-
There are no unit tests for the integration yet. When testing manually, avoid clicking real ads repeatedly; prefer intercepting `https://srv.carbonads.net/ads/*.json` with fixtures (e.g. in Playwright or the browser's developer tools).
58+
End-to-end tests live in `apps/site/tests/e2e/carbon-ads.spec.ts`, and impression accounting is unit tested in `apps/site/hooks/__tests__/useCarbonAd.test.jsx`. When testing manually, avoid clicking real ads repeatedly; prefer intercepting `https://srv.carbonads.net/ads/*.json` with fixtures (e.g. in Playwright or the browser's developer tools).

0 commit comments

Comments
 (0)