Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jest mocking api #133

Open
gloriaJun opened this issue Oct 8, 2021 · 0 comments
Open

jest mocking api #133

gloriaJun opened this issue Oct 8, 2021 · 0 comments
Assignees

Comments

@gloriaJun
Copy link
Owner

gloriaJun commented Oct 8, 2021

Date Mocking

const FIXED_SYSTEM_TIME = '2020-11-18T00:00:00Z';

describe('Set Fixed Date', () => {
    beforeEach(() => {
        jest.useFakeTimers('modern');
        jest.setSystemTime(Date.parse(FIXED_SYSTEM_TIME));
    });

    afterEach(() => {
        jest.useRealTimers();
    });
    
    it('Should reflect fixed date', () => {
        expect(new Date().toISOString()).toEqual(FIXED_SYSTEM_TIME);

        const MS_TO_ADVANCE = 5000;
        jest.advanceTimersByTime(MS_TO_ADVANCE);

        expect(new Date().toISOString()).toEqual(new Date(Date.parse(FIXED_SYSTEM_TIME) + MS_TO_ADVANCE).toISOString());
    });
});

Internal Module & promise type

import { getAccessToken } from './http-header-token';

jest.mock('@utils/token/token');
const TokenUtility = require('@utils/token/token');

describe('[http-header-token]', function () {
  let spy: jest.SpyInstance;

  beforeEach(() => {
    spy = jest.spyOn(TokenUtility, 'getAccessToken').mockReturnValue(Promise.resolve('accessToken'));
  });

  describe(`putConsentAgreement API`, function () {
    const apiUrl = '/customer/v1/consents';
    const data = {
      consents: [
        {
          sourceType: 'ONBOARD',
        },
      ],
    };

    it(`should be return undefined, source type is 'ONBOARD' and data is object`, async () => {
      const result = await getAccessToken({
        url: apiUrl,
        method: 'post',
        data,
      });

      expect(spy).toBeCalledTimes(0);
      expect(result).toBeUndefined();
    });

    it(`should be return undefined, source type is 'ONBOARD' and data is string`, function () {
      return expect(
        getAccessToken({
          url: apiUrl,
          method: 'post',
          data: JSON.stringify(data),
        })
      ).resolves.toBeUndefined();
    });
  });
});

Class type mocking

import { HttpConstants } from '@constants';
import { i18n } from '@utils/locale';
import FivuAPI from '@store/api/FivuAPI';
import { mockWindonwLocation } from '@tests/utility';
import { generateHttpCommonHeader } from './http-gen';

const { HEADER_NAMES } = HttpConstants;

const XSRF_TOKEN = 'xsrfToken';
const STORED_LINE_USER_ID = 'storedLineUserId';
const CONTEXT_LINE_USER_ID = 'contextLineUserId';
const ACCESS_TOKEN = 'accessToken';
const NATIVE_INFO = {...};

jest.mock('@store/registry', () => {
  return {
    getState: jest.fn(),
    getReducer: () => {
      return {
        xsrfTokenSelector: () => XSRF_TOKEN,
        userInfoSelector: () => STORED_USER_ID,
      };
    },
  };
});

jest.mock('@store/api/FivuAPI', () => {
  return {
    getContext: jest.fn(),
    getAccessToken: () => ACCESS_TOKEN,
    finGetNativeInfo: jest.fn(),
  };
});

describe('generateHttpCommonHeader', function () {
  it(`should be set X_LINE_USER_ID by store , if device context is empty`, async () => {
    // @ts-ignore
    jest.spyOn(FivuAPI, 'getContext').mockReturnValue({});

    const result = await generateHttpCommonHeader()();

    expect(result[HEADER_NAMES.X_USER_ID]).toBe(STORED_USER_ID);
  });

  it(`should be set X_LINE_USER_ID by native , if device context is not empty`, async () => {
    // @ts-ignore
    jest.spyOn(FivuAPI, 'getContext').mockReturnValue({ userId: CONTEXT_USER_ID });

    const result = await generateHttpCommonHeader()();

    expect(result[HEADER_NAMES.X_USER_ID]).toBe(CONTEXT_LINE_USER_ID);
  });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant