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

feat: add support and tests for webpack #45

Merged
merged 8 commits into from
Feb 12, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ coverage
package-lock.json
yarn.lock
.vscode
dist/
30 changes: 30 additions & 0 deletions browser-test/browser-test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#!/bin/sh

# Copyright 2019, Google, LLC.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

node build/browser-test/webserver.js &
while : ; do
if curl http://localhost:3000/path > /dev/null 2>&1 ; then
break
fi
echo '[script] Still waiting for server to start...'
sleep 1
done

echo '[script] Server is running, starting Karma!'
npx karma start
result=$?
echo "[script] Karma has finished with code $result"
wait
exit $result
26 changes: 26 additions & 0 deletions browser-test/test.browser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import * as assert from 'assert';

import {request} from '../src/index';
const port = 3000; // should match the port defined in `webserver.ts`

describe('💻 browser tests', async () => {
it('should just work from browser', async () => {
const result = await request({url: `http://localhost:${port}/path`});
assert.strictEqual(result.status, 200);
assert.strictEqual(result.data, 'response');
});

it('should pass querystring parameters from browser', async () => {
const result = await request({
url: `http://localhost:${port}/querystring`,
params: {query: 'value'}
});
assert.strictEqual(result.status, 200);
assert.strictEqual(result.data, 'value');
});

after(async () => {
const result = await request({url: `http://localhost:${port}/enough`});
// webserver will die now
});
});
36 changes: 36 additions & 0 deletions browser-test/webserver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import * as express from 'express';
import * as http from 'http';

const port = 3000;

function main() {
const app = express();
let server: http.Server;
app.get('/path', (req: express.Request, res: express.Response) => {
if (req.header('origin')) {
res.set('Access-Control-Allow-Origin', req.header('origin'));
}
res.send('response');
});
app.get('/querystring', (req: express.Request, res: express.Response) => {
if (req.header('origin')) {
res.set('Access-Control-Allow-Origin', req.header('origin'));
}
const query = req.query.query;
res.send(query || '');
});
app.get('/enough', (req: express.Request, res: express.Response) => {
if (req.header('origin')) {
res.set('Access-Control-Allow-Origin', req.header('origin'));
}
res.send('have a great rest of your day');
server.close();
console.log(`[http server] I'm no longer listening on port ${port}!`);
process.exit(0);
});
server = app.listen(port, () => {
console.log(`[http server] I'm listening on port ${port}!`);
});
}

main();
95 changes: 95 additions & 0 deletions karma.conf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/**
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// Karma configuration
// Use `npm run browser-test` to run browser tests with Karma.
const isDocker = require('is-docker')();

const webpackConfig = require('./webpack-tests.config.js');
process.env.CHROME_BIN = require('puppeteer').executablePath();

module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',

// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha'],

// list of files / patterns to load in the browser
files: ['./browser-test/test.*.ts'],

// list of files / patterns to exclude
exclude: [],

// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'./src/*.ts': ['coverage'],
'./src/**/*.ts': ['coverage'],
'./browser-test/*.ts': ['webpack', 'sourcemap']
},

webpack: webpackConfig,

// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'coverage', 'remap-coverage'],

coverageReporter: { type: 'in-memory' },
remapCoverageReporter: { html: './coverage' },

// web server port
port: 9876,

// enable / disable colors in the output (reporters and logs)
colors: true,

// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,

// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,

// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['ChromeCustom'],
customLaunchers: {
ChromeCustom: {
base: 'ChromeHeadless',
// We must disable the Chrome sandbox when running Chrome inside Docker (Chrome's sandbox needs
// more permissions than Docker allows by default)
flags: isDocker ? ['--no-sandbox'] : []
}
},

// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,

// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,

// set correct MIME type when serving .ts files (already compiled to JavaScript):
mime: {
'text/javascript': ['ts']
}
});
};
22 changes: 20 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
"prepare": "npm run compile",
"pretest": "npm run compile",
"codecov": "nyc report --reporter=json && codecov -f coverage/*.json",
"commitlint": "git log -1 --pretty=%B | commitlint"
"commitlint": "git log -1 --pretty=%B | commitlint",
"webpack": "webpack",
"browser-test": "sh browser-test/browser-test.sh"
},
"repository": "JustinBeckwith/gaxios",
"keywords": [
Expand All @@ -28,6 +30,7 @@
"devDependencies": {
"@commitlint/cli": "^7.2.1",
"@commitlint/config-conventional": "^7.1.2",
"@types/express": "^4.16.1",
"@types/extend": "^3.0.0",
"@types/mocha": "^5.2.5",
"@types/nock": "^9.3.0",
Expand All @@ -36,15 +39,30 @@
"@types/sinon": "^7.0.0",
"assert-rejects": "^1.0.0",
"codecov": "^3.0.4",
"express": "^4.16.4",
"gts": "^0.9.0",
"is-docker": "^1.1.0",
"karma": "^4.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-coverage": "^1.1.2",
"karma-firefox-launcher": "^1.1.0",
"karma-mocha": "^1.3.0",
"karma-remap-coverage": "^0.1.5",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^3.0.5",
"mocha": "^5.2.0",
"nock": "^9.6.0",
"null-loader": "^0.1.1",
"nyc": "^12.0.2",
"puppeteer": "^1.12.2",
"semantic-release": "^15.13.2",
"semistandard": "^13.0.1",
"sinon": "^7.1.1",
"source-map-support": "^0.5.6",
"typescript": "~3.3.0"
"ts-loader": "^5.3.3",
"typescript": "~3.3.0",
"webpack": "^4.29.3",
"webpack-cli": "^3.2.3"
},
"dependencies": {
"extend": "^3.0.2",
Expand Down
6 changes: 4 additions & 2 deletions src/gaxios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@ import {Agent} from 'https';
import fetch, {Response} from 'node-fetch';
import * as qs from 'querystring';
import * as stream from 'stream';
import {URL} from 'url';
import * as URL from 'url';

import {GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse, Headers} from './common';
import {isBrowser} from './isbrowser';
import {getRetryConfig} from './retry';

// tslint:disable-next-line variable-name no-any
Expand Down Expand Up @@ -148,7 +149,8 @@ export class Gaxios {
opts.method = opts.method || 'GET';

if (opts.params) {
const parts = new URL(opts.url);
const parts =
isBrowser() ? new window.URL(opts.url) : new URL.URL(opts.url);
parts.search = opts.paramsSerializer(opts.params);
opts.url = parts.href;
}
Expand Down
19 changes: 19 additions & 0 deletions src/isbrowser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

export function isBrowser(): boolean {
return typeof (window) !== 'undefined';
}
2 changes: 2 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
{
"extends": "./node_modules/gts/tsconfig-google.json",
"compilerOptions": {
"lib": ["es2015", "dom"],
"rootDir": ".",
"outDir": "build"
},
"include": [
"src/*.ts",
"test/*.ts",
"browser-test/*.ts",
"system-test/*.ts"
]
}
48 changes: 48 additions & 0 deletions webpack-tests.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// Use `npm run webpack` to produce Webpack bundle for this library.

const path = require('path');

module.exports = {
resolve: {
extensions: ['.ts', '.js', '.json'],
alias: {
'../../package.json': path.resolve(__dirname, 'package.json')
}
},
node: {
child_process: 'empty',
fs: 'empty',
crypto: 'empty'
},
module: {
rules: [
{
test: /node_modules\/https-proxy-agent\//,
use: 'null-loader'
},
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
mode: 'production',
plugins: []
};
Loading