Tuesday, 20 August 2019

How can I test a class which contains methods in it?

This is my first time working with tests and I get the trick to test UI components. Now I am attempting to test a class which has some static methods in it. It contains parameters too.

See the class:

import UserInfoModel from '../models/UserInfo.model';
import ApiClient from './apiClient';
import ApiNormalizer from './apiNormalizer';
import Article from '../models/Article.model';
import Notification from '../models/Notification.model';
import Content from '../models/Link.model';

export interface ResponseData {
  [key: string]: any;
}

export default class ApiService {
  static makeApiCall(
    url: string,
    normalizeCallback: (d: ResponseData) => ResponseData | null,
    callback: (d: any) => any
  ) {
    return ApiClient.get(url)
      .then(res => {
        callback(normalizeCallback(res.data));
      })
      .catch(error => {
        console.error(error);
      });
  }


  static getProfile(callback: (a: UserInfoModel) => void) {
    return ApiService.makeApiCall(`profile`, ApiNormalizer.normalizeProfile, callback);
  }
}

I already created a small test which is passing but I am not really sure about what I am doing.

// @ts-ignore
import moxios from 'moxios';
import axios from 'axios';
import { baseURL } from './apiClient';
import { dummyUserInfo } from './../models/UserInfo.model';

describe('apiService', () => {
  let axiosInstance: any;

  beforeEach(() => {
    axiosInstance = axios.create();
    moxios.install();
  });

  afterEach(() => {
    moxios.uninstall();
  });

  it('should perform get profile call', done => {
    moxios.stubRequest(`${baseURL.DEV}profile`, {
      status: 200,
      response: {
        _user: dummyUserInfo
      }
    });

    axiosInstance
      .get(`${baseURL.DEV}profile`)
      .then((res: any) => {
        expect(res.status).toEqual(200);
        expect(res.data._user).toEqual(dummyUserInfo);
      })
      .finally(done);
  });
});

I am using moxios to test the axios stuff -> https://github.com/axios/moxios

So which could be the proper way to test this class with its methods?



from How can I test a class which contains methods in it?

No comments:

Post a Comment