Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  1. Does it call useQuery with the correct queryKey array?

  2. Does it call queryFn useQuery with the expected fetch queryFn method?

  3. Does it return the status fields from they query?

  4. Does it return camel-case’d data response from the query (or {} if empty)?

...

Code Block
languagejs
// ...api-src/hooks/api.test.ts
import { useCamelCaseObject } from '@edx/frontend-platform';
import { when } from 'jest-when';

jest.mock('@tanstack/react-query', () => ({
  useQuery: jest.fn()
  useMutation: jest.fn(({ mutationFn }) => ({ mutationFn })),
}));

const mockUseQueryForUserData = (response) => {
  when(useQuery)
    .calledWith(expect.objectContaining({ queryKey: [queryKeys.userData] }))
    .mockImplementation(({ queryKey, queryFn }) => ({
      data: response,
      queryKey,
      queryFn,
    });
}
let out;
const userId = 'test-user-id';
const response = { test-field: 'user-response' };
describe('api hooks', () => {
  describe('useUserData', () => {
    beforeEach(() => {
      mockUseQueryForUserData(response);
      out = hooks.useUserData(userId);      
    });
    
    // Does it call useQuery with the correct queryKey array?
    it('initializes query with userData queryKey and user ID', () => {
      expect(out.queryKey).toEqual([queryKeys.userData, userId]);
    });
    
    // Does it call queryFn with the expected fetch method?
    it('initializes query with <my get behavior>', () => {
      // Mock/test your fetch method by calling out.queryFn()
    });

    // Does it return the status fields from they query?
    -- Add status test from repo
    
    // Does it return camel-case’d data response from the query (or {} if empty)?
    it('returns camelCase object from data if data has been returned', () => {
      expect(out.data).toEqual(camelCaseObject(response));
    });
   
     // Does it return camel-case’d data response from the query (or {} if empty)?
    it('returns empty object from data if data has not been returned', () => {
      mockUseQueryForUserData(undefined);
      out = hooks.useUserData(userId);
      expect(out.data).toEqual({});
    })
  });
  // ...test system data in similar pattern.
});

...