( filename: string, source: string, runAfterServer?: () => void )
| 31 | } |
| 32 | |
| 33 | export async function testSSR( |
| 34 | filename: string, |
| 35 | source: string, |
| 36 | runAfterServer?: () => void |
| 37 | ): Promise<void> { |
| 38 | // Transform the code with babel so JSX becomes JS. |
| 39 | source = babel.transformSync(source, { |
| 40 | filename, |
| 41 | plugins: ['@babel/plugin-syntax-import-attributes'] |
| 42 | }).code; |
| 43 | |
| 44 | // Send the HTML along with the source code to the worker to be hydrated in a DOM environment. |
| 45 | return new Promise((resolve, reject) => { |
| 46 | let req = http.request( |
| 47 | { |
| 48 | hostname: 'localhost', |
| 49 | port: 18235, |
| 50 | method: 'POST', |
| 51 | headers: { |
| 52 | 'Content-Type': 'application/json' |
| 53 | } |
| 54 | }, |
| 55 | res => { |
| 56 | let body = ''; |
| 57 | res.setEncoding('utf8'); |
| 58 | res.on('data', chunk => { |
| 59 | body += chunk; |
| 60 | }); |
| 61 | |
| 62 | res.on('end', () => { |
| 63 | if (res.statusCode !== 200) { |
| 64 | let data = JSON.parse(body); |
| 65 | reject(new Error(data.errors[0])); |
| 66 | return; |
| 67 | } |
| 68 | |
| 69 | // Capture React errors/warning and make them fail the tests. |
| 70 | let errors: string[] = []; |
| 71 | console.error = console.warn = (...messages) => { |
| 72 | errors.push(util.format(...messages)); |
| 73 | }; |
| 74 | |
| 75 | // Evaluate the code to get a React element, and hydrate into the dom. |
| 76 | try { |
| 77 | document.body.innerHTML = `<div id="root">${body}</div>`; |
| 78 | let container = document.querySelector('#root'); |
| 79 | runAfterServer?.(); |
| 80 | let element = evaluate(source, filename); |
| 81 | if (ReactDOMClient) { |
| 82 | act(() => |
| 83 | ReactDOMClient.hydrateRoot(container, <SSRProvider>{element}</SSRProvider>) |
| 84 | ); |
| 85 | } else { |
| 86 | act(() => { |
| 87 | (ReactDOM as any).hydrate(<SSRProvider>{element}</SSRProvider>, container); |
| 88 | }); |
| 89 | } |
| 90 | } catch (err: any) { |
no test coverage detected