fix: throw for unset `createContext` get on the server (#17580)

* fix: throw for unset `createContext` get on the server

* smol tweak

---------

Co-authored-by: Rich Harris <rich.harris@vercel.com>
pull/17564/head
Paolo Ricciuti 6 months ago committed by GitHub
parent 1c131f11ca
commit 2d62ffee9c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: throw for unset `createContext` get on the server

@ -17,7 +17,17 @@ export function set_ssr_context(v) {
*/
export function createContext() {
const key = {};
return [() => getContext(key), (context) => setContext(key, context)];
return [
() => {
if (!hasContext(key)) {
e.missing_context();
}
return getContext(key);
},
(context) => setContext(key, context)
];
}
/**

@ -0,0 +1,5 @@
import { test } from '../../test';
export default test({
error: 'missing_context'
});

@ -0,0 +1,9 @@
<script module>
import { createContext } from 'svelte';
const [get] = createContext();
</script>
<script>
get();
</script>

@ -12,6 +12,7 @@ import { assert_html_equal_with_options } from '../html_equal.js';
import { suite_with_variants, type BaseTest } from '../suite.js';
import type { CompileOptions } from '#compiler';
import { seen } from '../../src/internal/server/dev.js';
import type { SyncRenderOutput } from '#server';
interface SSRTest extends BaseTest {
mode?: ('sync' | 'async')[];
@ -76,6 +77,9 @@ const { test, run } = suite_with_variants<SSRTest, 'sync' | 'async', CompileOpti
let rendered;
let errored = false;
let body: SyncRenderOutput['body'];
let head: SyncRenderOutput['head'];
let hashes: SyncRenderOutput['hashes'];
try {
const render_result = render(Component, {
props: config.props || {},
@ -83,6 +87,8 @@ const { test, run } = suite_with_variants<SSRTest, 'sync' | 'async', CompileOpti
csp: config.csp
});
rendered = is_async ? await render_result : render_result;
// we need to access these inside the try-catch otherwise errors in the script tag are not caught
({ body, head, hashes } = rendered);
} catch (error) {
errored = true;
if (config.error) {
@ -97,8 +103,6 @@ const { test, run } = suite_with_variants<SSRTest, 'sync' | 'async', CompileOpti
assert.fail('Expected an error to be thrown, but rendering succeeded.');
}
const { body, head, hashes } = rendered;
fs.writeFileSync(
`${test_dir}/_output/${is_async ? 'async_rendered.html' : 'rendered.html'}`,
body

Loading…
Cancel
Save