Best practices and strategies for unit tests #177
Replies: 2 comments 1 reply
-
What you could do is mocking the underlying http requests and return some of your own data for testing. If you just use |
Beta Was this translation helpful? Give feedback.
-
I'm currently using the BUT, when i was pretty confident with the solution, i tried the same method with the mutations and didn't succeeded. Here is my code for the query: The service: public myQueryObservableFunction(): Observable<QueryObserverResult<MyResponse>> {
return this.query({
queryKey: ['queryKey'],
queryFn: () => this.http.get<MyResponse>( 'apiurl'),
}).result$;
} The unit test: afterEach(() => {
httpTestingController.verify();
});
it('get should succeed', fakeAsync(() => {
let lastResponse = undefined;
myQueryObservableFunction().subscribe((response) => {
lastResponse = response;
});
const request = httpTestingController.expectOne({
method: 'GET',
url: 'apiurl',
});
request.flush(responseDTO);
flush();
expect(lastResponse).toEqual(
expect.objectContaining({
data: expectedData,
}),
);
})); But for the mutation it fails on The service: public create(param: MyParam): Observable<MutationObserverResult<void, Error, MyParam>> {
const mutation = this.mutation<void, Error, MyParam>({
mutationKey: ['create'],
mutationFn: (data) => this.http.post<void>(
'apiurl/create',
data,
),
});
mutation.mutate(param);
return mutation.result$;
} The unit test: afterEach(() => {
httpTestingController.verify();
});
it('post should succeed', fakeAsync(() => {
let lastResponse = undefined;
create(fakeParams).subscribe((response) => {
lastResponse = response;
});
const request = httpTestingController.expectOne('apiurl/create');
request.flush(null);
flush();
expect(lastResponse).toEqual(
expect.objectContaining({
data: undefined,
variables: fakeParams,
}),
);
})); |
Beta Was this translation helpful? Give feedback.
-
Hi everyone. I'm wondering how you normally proceed with unit-testing services which rely on this library.
It would be super nice if you can share which strategies you normally use.
Example: if you are unit-testing a service which imports "injectQueryClient", "injectMutation" and "injectQuery", what do you normally do?
I'd appreciate if you can share a bit about this topic.
Beta Was this translation helpful? Give feedback.
All reactions