Skip to content
loading...

re: Testing Svelte stores and mocking dependencies VIEW POST

FULL DISCUSSION
 

Under "Rewriting the CallbackComponent specs" am I right to assume that the "displays the initial price" test is not correct as per the implementation? The initial price should be set by the fetch call (which is stubbed to 99.99). By setting the store value directly you are just duplicating the next test case making them redundant (if set works it works).

Should it be re-written like so as to test being set by fetch?

it("displays the initial price", async () => {
mount(CallbackComponent);
await tick();
expect(container.textContent).toContain("The price is: $99.99");
});

Also, I seem to need like 5 "ticks" or else the test case will fail. Any idea why? is there a danger in using too many ticks?

 

Thanks for pointing this out, I think I just did a poor job of explaining it so I’ll try to rewrite this to make it clearer.

This middle section is mid-refactor which is part of the trouble. Because I'm refactoring the code by extracting the fetch logic into a store, the tests for CallbackComponent should no longer care about fetch at all.

The test displays the initial price that doesn’t care so much about how the data is retrieved, it just cares that the Svelte subscription for price is set up correctly.

But the test with the set AND the fetch stub is a half-way house between the old version and the new version. The final section of this post removes the need to stub window.fetch by instead stubbing out fetchPrice instead. That is a good thing because the tests for CallbackComponent then have no knowledge of how fetchPrice works (i.e. by calling window.fetch, just like the component itself.

I’m still not sure if I’m doing a good job of describing this--let me know if this has helped!

code of conduct - report abuse