Add examples on how to test trackedFunction
chsanch opened this issue · comments
Hi, I have the following trackedFunction to populate a table (using ember-headless-table) and also I'm using Supabase to fetch the data, so in my "Table" component I have the following :
request = trackedFunction(this, async () => {
const { data, count, error } = await this.supabase.client
.from('table')
.select('*', { count: 'exact' })
.range(this.start, this.end);
return data;
});
this.start
and this.end
are @tracked
variables, so each time they change the function is triggered, that work as expected.
The issue I have is on a simple Integration test for this component:
await render(hbs`<TableComponent />`);
will trigger the request to Supabase, which throws an error because it need the Supabase env variables (url, key, etc).
Is there a way to prevent trackedFunction
from executing the API request on the tests?
resources aren't mockable or anything like that -- their behaviors are private to their consumers, much like the router, or component rendering is a private detail. There are options though!
What I wrote before
there is not -- the thing you'd want to mock here is the supabase client -- is that a service?
if not, you'd probably want to make it one, like:
// app/services/tables.js
import Service from '@ember/service';
export default Tables extends Service {
// methods here
allExact(start, end) { /* ... */ }
}
This does restrict the amount of flexibility you have in your component, but it allows you to, in your test do:
const myMockData = [];
this.owner.register('service:tables', class extends {
allExact(start, end) {
return myMockData;
}
});
Supabase has enough fluent-builder-API, that I would hope for a test-mode, or some way to hook it up to MSW
using MSW is a great way to keep your data as-is, not do any services, and have as-real-as-it-gets mocking in your app
I have a demo on how to set up MSW for testing in these commits: https://github.com/NullVoxPopuli/ember-msw-development/commits/main
And in this repo: https://github.com/NullVoxPopuli/ember-data-resources/blob/main/tests/unit/find-all-test.ts#L16
I see, in. my case I have a supabase
service, so probably the best solution is to mock it, thanks for the suggestion!
Should I close this ticket then?
I can, no worries - glad you have a path forward!