Skip to content
This repository has been archived by the owner on Dec 3, 2021. It is now read-only.

Commit

Permalink
test: Update tests (#27)
Browse files Browse the repository at this point in the history
* test: Update jest settings

* test: Update components tests

* test: Update utils tests

* chore: Remove unused deps

* ci: Skipping Node 6
  • Loading branch information
adambrgmn committed Aug 15, 2018
1 parent 27e65e3 commit ddbed5d
Show file tree
Hide file tree
Showing 10 changed files with 156 additions and 420 deletions.
1 change: 0 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ notifications:
node_js:
- '9'
- '8'
- '6'

script: yarn test --coverage && yarn build

Expand Down
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module.exports = {
setupFiles: ['<rootDir>/tests/setup.js'],
setupTestFrameworkScriptFile: '<rootDir>/tests/setup-framework.js',
collectCoverageFrom: [
'src/**/*.{js,jsx}',
'!**/node_modules/**',
Expand Down
7 changes: 3 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@
"babel-preset-react": "^6.24.1",
"cz-conventional-changelog": "^2.1.0",
"doctoc": "^1.3.1",
"enzyme": "^3.2.0",
"enzyme-adapter-react-16": "^1.1.0",
"eslint": "^5.3.0",
"eslint-config-airbnb": "^17.0.0",
"eslint-config-prettier": "^3.0.1",
Expand All @@ -35,13 +33,14 @@
"husky": "^1.0.0-rc.13",
"isomorphic-fetch": "^2.2.1",
"jest": "^23.5.0",
"jest-dom": "^1.12.0",
"lint-staged": "^7.2.2",
"microbundle": "^0.6.0",
"nock": "^9.1.4",
"prettier": "^1.14.2",
"prop-types": "^15.6.0",
"react": "^16.1.1",
"react-dom": "^16.1.1"
"react-dom": "^16.1.1",
"react-testing-library": "^5.0.0"
},
"dependencies": {
"qs": "^6.5.1"
Expand Down
111 changes: 40 additions & 71 deletions src/OauthReceiver/OauthReceiver.test.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,17 @@
import React from 'react';
import { mount } from 'enzyme';
import { cleanup, render, waitForElement } from 'react-testing-library';
import qs from 'qs';
import nock from 'nock';
import { OauthReceiver } from './index';
import { fetch2 } from '../utils/fetch';

const delay = dur => new Promise(resolve => setTimeout(resolve, dur));
jest.mock('../utils/fetch.js', () => ({
fetch2: jest.fn(() => Promise.resolve({ access_token: 'foo' })),
}));

afterAll(() => nock.cleanAll());
afterEach(cleanup);

describe('with default fetch args', () => {
beforeAll(() => {
const api = nock('https://api.service.com/');

api
.post('/oauth2/token')
.query({
code: 'abc',
grant_type: 'authorization_code',
client_id: 'abc',
client_secret: 'abcdef',
redirect_uri: 'https://www.test.com/redirect',
})
.reply(200, {
access_token: '123',
token_type: 'bearer',
account_id: '123456',
});
});

test('Component <OauthReceiver />', async () => {
describe('Component <OauthReceiver />', () => {
test('with default fetch args', async () => {
const onAuthSuccess = jest.fn();
const onAuthError = jest.fn();

Expand All @@ -39,72 +22,38 @@ describe('with default fetch args', () => {
redirectUri: 'https://www.test.com/redirect',
querystring: `?${qs.stringify({
code: 'abc',
state: JSON.stringify({ from: '/settings' }),
state: JSON.stringify({ from: '/success' }),
})}`,
onAuthSuccess,
onAuthError,
};

const wrapper = mount(
const { getByTestId } = render(
<OauthReceiver
{...props}
render={({ processing, state }) => (
<div>
<span className="processing">{processing ? 'yes' : 'no'}</span>
<span className="state">{state && state.from}</span>
{processing && <span data-testid="done">done</span>}
<span data-testid="state">{state && state.from}</span>
</div>
)}
/>,
);

expect(wrapper.find('.processing').text()).toBe('yes');
await delay(10);
expect(wrapper.find('.processing').text()).toBe('no');
expect(wrapper.find('.state').text()).toBe('/settings');
await waitForElement(() => getByTestId('done'));

const successCall = onAuthSuccess.mock.calls[0];
expect(onAuthSuccess.mock.calls.length).toBe(1);
expect(successCall[0]).toBe('123');
expect(successCall[1]).toEqual({
response: {
access_token: '123',
token_type: 'bearer',
account_id: '123456',
},
state: { from: '/settings' },
});
expect(onAuthSuccess).toHaveBeenCalledTimes(1);
expect(onAuthError).not.toHaveBeenCalled();

expect(onAuthError.mock.calls.length).toBe(0);
expect(getByTestId('state')).toHaveTextContent('/success');
});
});

describe('with custom token uri fetch args', () => {
let api = null;

beforeAll(() => {
api = nock('https://api.service.com/', {
reqheaders: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});

api
.get('/oauth2/token')
.query({
code: 'abc',
grant_type: 'authorization_code',
client_id: 'abc',
client_secret: 'abcdef',
redirect_uri: 'https://www.test.com/redirect',
})
.reply(200, {});
});
test('with custom token uri fetch args', async () => {
fetch2.mockClear();

test('Component <OauthReceiver /> with fetch args', async () => {
const props = {
tokenUrl: 'https://api.service.com/oauth2/token',
tokenFetchArgs: {
method: 'GET',
cache: 'no-cache',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
},
Expand All @@ -117,8 +66,28 @@ describe('with custom token uri fetch args', () => {
})}`,
};

mount(<OauthReceiver {...props} render={() => <div />} />);
const { getByTestId } = render(
<OauthReceiver
{...props}
render={({ processing }) => (
<div>{processing && <span data-testid="done">done</span>}</div>
)}
/>,
);

expect(api.isDone()).toBe(true);
await waitForElement(() => getByTestId('done'));

expect(fetch2).toHaveBeenCalledWith(
expect.stringContaining(props.tokenUrl),
expect.objectContaining({
method: expect.stringMatching('POST'),
cache: expect.stringMatching('no-cache'),
headers: expect.objectContaining({
'Content-Type': expect.stringMatching(
'application/x-www-form-urlencoded',
),
}),
}),
);
});
});
19 changes: 10 additions & 9 deletions src/OauthSender/OauthSender.test.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,30 @@
/* eslint-disable react/destructuring-assignment */
/* eslint-disable react/prop-types */
import React from 'react';
import { shallow } from 'enzyme';
import { render, cleanup } from 'react-testing-library';
import { OauthSender } from './index';
import { buildURL } from '../utils';

afterEach(cleanup);

test('Component: <OauthSender />', () => {
const props = {
authorizeUrl: 'https://www.service.com/oauth2/authorize',
clientId: 'abc',
redirectUri: 'https://www.test.com/redirect',
render: (
{ url }, // eslint-disable-line
) => (
<a className="link" href={url}>
render: ({ url }) => (
<a data-testid="link" href={url}>
Connect
</a>
),
};

const wrapper = shallow(<OauthSender {...props} />);
const expectedUrl = buildURL(`${props.authorizeUrl}`, {
const { getByTestId } = render(<OauthSender {...props} />);

const expectedUrl = buildURL(props.authorizeUrl, {
client_id: props.clientId,
redirect_uri: props.redirectUri,
response_type: 'code',
});

expect(wrapper.find('.link').prop('href')).toEqual(expectedUrl);
expect(getByTestId('link')).toHaveAttribute('href', expectedUrl);
});
13 changes: 3 additions & 10 deletions src/utils/index.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,12 @@
// @flow
import qs from 'qs';
import { fetch2 } from './fetch';

function buildURL(url, params, paramsSerializer): string {
function buildURL(url, params) {
if (params == null) return url;

let serializedParams;

if (paramsSerializer != null) {
serializedParams = paramsSerializer(params);
} else {
serializedParams = qs.stringify(params);
}

const serializedParams = qs.stringify(params)
if (!serializedParams) return url;

return `${url}${url.indexOf('?') < 0 ? '?' : '&'}${serializedParams}`;
}

Expand Down
39 changes: 5 additions & 34 deletions src/utils/utils.test.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,14 @@
import nock from 'nock';
import * as utils from './index';

beforeAll(() => {
const api = nock('https://api.github.com/');

api.get('/users/octocat').reply(200, {
login: 'octocat',
});

api.get('/users/404').reply(404, {
message: 'User 404 not found',
});
});

test('utils.buildURL', () => {
const baseUrl = 'https://www.test.com';

let url = utils.buildURL(baseUrl, {
expect(utils.buildURL(baseUrl, {
a: 'hello',
b: 'world',
});
expect(url).toEqual(`${baseUrl}?a=hello&b=world`);

url = utils.buildURL(baseUrl);
expect(url).toBe(baseUrl);

url = utils.buildURL(`${baseUrl}?a=hello`, { b: 'world' });
expect(url).toBe(`${baseUrl}?a=hello&b=world`);
});

test('utils.fetch2', async () => {
const data = await utils.fetch2('https://api.github.com/users/octocat');
expect(data.login).toBe('octocat');
})).toEqual(`${baseUrl}?a=hello&b=world`);

try {
await utils.fetch2('https://api.github.com/users/404');
expect(true).toBe(false);
} catch (err) {
expect(err.response.ok).toBe(false);
expect(err.message).toBe('Not Found');
}
expect(utils.buildURL(baseUrl)).toBe(baseUrl);
expect(utils.buildURL(`${baseUrl}?a=hello`, { b: 'world' })).toBe(`${baseUrl}?a=hello&b=world`);
expect(utils.buildURL(baseUrl, {})).toBe(baseUrl);
});
1 change: 1 addition & 0 deletions tests/setup-framework.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import 'jest-dom/extend-expect';
5 changes: 0 additions & 5 deletions tests/setup.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,2 @@
/* eslint-disable import/first */
import './raf-polyfill';
import 'isomorphic-fetch';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });
Loading

0 comments on commit ddbed5d

Please sign in to comment.