Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How could I set a private svelte variable for the unit testing?

How could I set a private svelte variable for the unit testing?

E.g. I have the component:

//a.svelte
<script>
    let a = "b";
</script>

<div data-testid="c">{a}</div>

And I am trying to test the component:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { screen } from "@testing-library/svelte";
import a from "./a.svelte;

...

//arrange
const aMock = "d";

//act
render(a);

//assert
expect(screen.getByTestId("c").textContent).toBe("d");

How can I set the a inside the a.svelte? I do not want to make the a a property, i.e. I do not want to do the export let a = "b";. I want to keep a as an internal state of the component, but I would like to mock it.

>Solution :

If you compile with the dev flag, you will get additional functions on the component for capturing and setting component state, e.g. the default REPL with its name state generates:

$$self.$capture_state = () => ({ name });

$$self.$inject_state = $$props => {
    if ('name' in $$props) $$invalidate(0, name = $$props.name);
};

if ($$props && "$$inject" in $$props) {
    $$self.$inject_state($$props.$$inject);
}

You can also inject an initial state via $$inject as part of the props.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading