|
| 1 | +import { nextTestSetup } from 'e2e-utils' |
| 2 | + |
| 3 | +describe('next/dynamic with CSP nonce', () => { |
| 4 | + const { next } = nextTestSetup({ |
| 5 | + files: __dirname, |
| 6 | + }) |
| 7 | + |
| 8 | + it('should include nonce attribute on preload links generated by next/dynamic', async () => { |
| 9 | + const $ = await next.render$('/') |
| 10 | + |
| 11 | + // Check that preload links have the nonce attribute |
| 12 | + const preloadLinks = $('link[rel="preload"]') |
| 13 | + |
| 14 | + const dynamicPreloadLinks = preloadLinks.filter((_, element) => { |
| 15 | + const $element = $(element) |
| 16 | + const href = $element.attr('href') |
| 17 | + return href && href.includes('_next/static/chunks/') |
| 18 | + }) |
| 19 | + |
| 20 | + // There should be at least one preload link for dynamic chunks |
| 21 | + expect(dynamicPreloadLinks.length).toBeGreaterThan(0) |
| 22 | + |
| 23 | + dynamicPreloadLinks.each((_, element) => { |
| 24 | + const $element = $(element) |
| 25 | + const href = $element.attr('href') |
| 26 | + |
| 27 | + // Only check preload links for dynamic chunks |
| 28 | + if (href && href.includes('_next/static/chunks/')) { |
| 29 | + expect($element.attr('nonce')).toBe('test-nonce') |
| 30 | + } |
| 31 | + }) |
| 32 | + }) |
| 33 | + |
| 34 | + it('should not generate CSP violations when using next/dynamic with nonce', async () => { |
| 35 | + const browser = await next.browser('/') |
| 36 | + |
| 37 | + // Wait for the dynamic component to load |
| 38 | + await browser.waitForElementByCss('#dynamic-component-loaded') |
| 39 | + |
| 40 | + // OPTIMIZATION: Get both text values concurrently |
| 41 | + const [pageTitle, componentText] = await Promise.all([ |
| 42 | + browser.elementByCss('#page-title').then((el) => el.text()), |
| 43 | + browser.elementByCss('#dynamic-component-loaded').then((el) => el.text()), |
| 44 | + ]) |
| 45 | + |
| 46 | + expect(pageTitle).toBe('CSP Nonce Test Page') |
| 47 | + expect(componentText).toBe('Dynamic component loaded successfully') |
| 48 | + |
| 49 | + // Check for CSP violations in Chrome (most expensive operation) |
| 50 | + if (global.browserName === 'chrome') { |
| 51 | + const logs = await browser.log() |
| 52 | + const cspViolations = logs.filter( |
| 53 | + (log) => |
| 54 | + log.source === 'security' && |
| 55 | + log.message.includes('Content Security Policy') |
| 56 | + ) |
| 57 | + |
| 58 | + expect(cspViolations).toEqual([]) |
| 59 | + } |
| 60 | + }) |
| 61 | +}) |
0 commit comments