Skip to content

Commit

Permalink
Added tests, mocking the axios object
Browse files Browse the repository at this point in the history
  • Loading branch information
icellan committed Apr 26, 2021
1 parent 855ccc0 commit d5ddea7
Show file tree
Hide file tree
Showing 4 changed files with 239 additions and 10 deletions.
13 changes: 3 additions & 10 deletions lib/api-client.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
const axios = require('axios'); // .default (@mrz what does this affect?)

export const tonicAxios = axios.create();

// Used internally for communication from req=>resp in axios
const internalHeaderKey = 'x-user-session-token';

// Current version for requests from the API
const pkgVersion = 'v0.1.77';
export const pkgVersion = 'v0.1.77';
export const apiVersion = 'v1';

// getOptions is a factory for axios default options
Expand Down Expand Up @@ -54,6 +51,8 @@ export const checkError = function (e) {

// This wraps axios for cookie management for API vs User session token
export const createApiClient = function (t) {
const tonicAxios = axios.create();

return {
async post(path, data, sessionToken = '') {
try {
Expand Down Expand Up @@ -85,9 +84,6 @@ export const createApiClient = function (t) {
throw checkError(e);
}
},
async putRaw(path, data, sessionToken = '') {
return this.put(path, data, sessionToken, true);
},
async get(path, sessionToken = '', rawResponse = false) {
try {
sessionToken = setUserToken(t, sessionToken);
Expand All @@ -104,9 +100,6 @@ export const createApiClient = function (t) {
throw checkError(e);
}
},
async getRaw(path, sessionToken = '') {
return this.get(path, sessionToken, true);
},
async delete(path, sessionToken = '') {
try {
sessionToken = setUserToken(t, sessionToken);
Expand Down
140 changes: 140 additions & 0 deletions test/api.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import axios from 'axios';
import {
describe,
expect,
beforeEach,
afterEach,
it,
} from '@jest/globals';
jest.mock('axios');
const mockAxios = jest.genMockFromModule('axios')
axios.create.mockImplementation(() => mockAxios);

import TonicPow from '../lib/api';
import { pkgVersion } from '../lib/api-client';

import advertiserData from './data/advertiser.json';
import campaignData from './data/campaign.json';

let tonicPow = '';
const fakeApiKey = '678d769317973b3802a89dc1b0ff3e8d';
const options = {
'headers': {
'User-Agent': `tonicpow-js ${pkgVersion}`,
api_key: fakeApiKey
},
withCredentials: true
};

describe('basic tests', function () {
beforeEach(function () {
tonicPow = new TonicPow(fakeApiKey);
jest.clearAllMocks();
});

it('createAdvertiserProfile', async () => {
// this only mocks the axios object, but not the Tonic Pow processing or wrappers
mockAxios.post.mockImplementationOnce(() => Promise.resolve({data: advertiserData.return}));

// test the api call
const response = await tonicPow.createAdvertiserProfile(advertiserData.create);
expect(response).toEqual(advertiserData.return);
expect(mockAxios.post).toHaveBeenCalledWith(
`https://api.tonicpow.com/v1/advertisers`,
advertiserData.create,
options,
);
expect(tonicPow.session.userToken).toEqual(undefined);
});

it('createAdvertiserProfile ERROR', async () => {
mockAxios.post.mockImplementationOnce(() => Promise.reject({
response: {
data: advertiserData.error
}
}));

await expect(tonicPow.createAdvertiserProfile({})).rejects.toEqual(advertiserData.error);
expect(mockAxios.post).toHaveBeenCalledWith(
`https://api.tonicpow.com/v1/advertisers`,
{},
options,
);
expect(tonicPow.session.userToken).toEqual(undefined);
});

it('createAdvertiserProfile with userSessionToken', async () => {
mockAxios.post.mockImplementationOnce(() => Promise.resolve({data: advertiserData.return}));

// the extra x-user-session-token should have been added to the request options
const userSessionToken = '__userSessionToken__';
const requestOptions = JSON.parse(JSON.stringify(options));
requestOptions.headers['x-user-session-token'] = userSessionToken;

// test the api call
const response = await tonicPow.createAdvertiserProfile(advertiserData.create, userSessionToken);
expect(response).toEqual(advertiserData.return);
expect(mockAxios.post).toHaveBeenCalledWith(
`https://api.tonicpow.com/v1/advertisers`,
advertiserData.create,
requestOptions,
);
expect(tonicPow.session.userToken).toEqual(userSessionToken);
});

it('getAdvertiserProfile', async () => {
mockAxios.get.mockImplementationOnce(() => Promise.resolve({data: advertiserData.return}));

// test the api call
const response = await tonicPow.getAdvertiserProfile(206);
expect(response).toEqual(advertiserData.return);
expect(mockAxios.get).toHaveBeenCalledWith(
`https://api.tonicpow.com/v1/advertisers/details/206`,
options,
);
expect(tonicPow.session.userToken).toEqual(undefined);
});

it('updateAdvertiserProfile', async () => {
mockAxios.put.mockImplementationOnce(() => Promise.resolve({data: advertiserData.return}));

// test the api call
const response = await tonicPow.updateAdvertiserProfile(advertiserData.update);
expect(response).toEqual(advertiserData.return);
expect(mockAxios.put).toHaveBeenCalledWith(
`https://api.tonicpow.com/v1/advertisers`,
advertiserData.update,
options,
);
expect(tonicPow.session.userToken).toEqual(undefined);
});

// ... add other tests here

it('createCampaign', async () => {
mockAxios.post.mockImplementationOnce(() => Promise.resolve({data: campaignData.return}));

// test the api call
const response = await tonicPow.createCampaign(campaignData.create);
expect(response).toEqual(campaignData.return);
expect(mockAxios.post).toHaveBeenCalledWith(
`https://api.tonicpow.com/v1/campaigns`,
campaignData.create,
options,
);
expect(tonicPow.session.userToken).toEqual(undefined);
});

it('getCampaign', async () => {
mockAxios.get.mockImplementationOnce(() => Promise.resolve({data: campaignData.return}));

// test the api call
const response = await tonicPow.getCampaign(243);
expect(response).toEqual(campaignData.return);
expect(mockAxios.get).toHaveBeenCalledWith(
`https://api.tonicpow.com/v1/campaigns/details/243`,
options,
);
expect(tonicPow.session.userToken).toEqual(undefined);
});
});
32 changes: 32 additions & 0 deletions test/data/advertiser.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"create": {
"name": "TonicPow",
"homepage_url": "https://tonicpow.com",
"icon_url": "https://tonicpow.com/images/apple-touch-icon.png"
},
"return": {
"domain_verified": false,
"homepage_url": "https://tonicpow.com",
"icon_url": "https://tonicpow.com/images/apple-touch-icon.png",
"id": 206,
"link_service_domain_id": 0,
"name": "TonicPow",
"user_id": 18,
"public_guid": "c48e32bb1ad54f36f43aa98686f5b82050b4bbd2d9e70f383e6cc2f8f6273fda",
"unlisted": false
},
"update": {
"id": 206,
"name": "TonicPow Now!"
},
"error": {
"code": 65,
"data": "",
"ip_address": "84.107.203.32",
"method": "POST",
"message": "missing required field: name",
"request_guid": "b62b07f0-5882-4fae-b68e-b35abe80449a",
"status_code": 422,
"url": "/v1/advertisers"
}
}
64 changes: 64 additions & 0 deletions test/data/campaign.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
{
"create": {
"advertiser_profile_id": 206,
"currency": "usd",
"description": "Earn BSV for sharing things you like.",
"image_url": "https://i.imgur.com/TbRFiaR.png",
"target_url": "https://tonicpow.com",
"title": "Checkout TonicPow",
"pay_per_click_rate": 0.01,
"contribute_enabled": true
},
"return": {
"advertiser_profile": {
"domain_verified": false,
"homepage_url": "https://tonicpow.com",
"icon_url": "https://tonicpow.com/images/apple-touch-icon.png",
"id": 206,
"link_service_domain_id": 0,
"name": "TonicPow Now!",
"user_id": 18,
"public_guid": "c48e32bb1ad54f36f43aa98686f5b82050b4bbd2d9e70f383e6cc2f8f6273fda",
"unlisted": false
},
"advertiser_profile_id": 206,
"balance": 0,
"balance_satoshis": 0,
"bot_protection": true,
"contribute_enabled": true,
"created_at": "2021-04-20T16:19:35.69Z",
"currency": "usd",
"description": "Earn BSV for sharing things you like.",
"domain_verified": false,
"expires_at": "",
"funding_address": "1HwZwEzDVvmGcjQCFojCmkCzyNyRRoeUT8",
"goals": null,
"id": 243,
"images": null,
"image_url": "https://i.imgur.com/TbRFiaR.png",
"last_event_at": "",
"links_created": 0,
"link_service_domain_id": 0,
"match_domain": true,
"paid_clicks": 0,
"paid_conversions": 0,
"pay_per_click_rate": 0.01,
"public_guid": "437608cef8ac45fa9e405dce2c75e0b8",
"requirements": {
"application": false,
"facebook": false,
"google": false,
"handcash": false,
"kyc": false,
"moneybutton": false,
"relay": false,
"twitter": false,
"visitor_countries": null,
"visitor_restrictions": false
},
"slug": "checkout-tonicpow",
"target_url": "https://tonicpow.com",
"title": "Checkout TonicPow",
"unlisted": false
}
}

0 comments on commit d5ddea7

Please sign in to comment.