Load testing with K6 & TypeScript

This article would showcase how to run a K6 load testing script written in typescript since developers are more focused on writing codes that involve type checking, as well as using the full potential of objected-oriented implementations.
Since K6 needs a .js (javascript) file extension to run, we would use babel & webpack to transpile and bundle our files.
Setup -
Let's create a basic typescript file that will post a request to an endpoint using K6 the code snippet is shown below -
import { sleep, check } from 'k6’;
import { Options } from 'k6/options’;
import http, { StructuredRequestBody } from 'k6/http’;
const binFile = open(’test.png’, 'b’);
const url = `https://httpbin.org/post`;
export let options: Options = {
vus: 5,
duration: '10s'
};export default (): void => {
const postData: StructuredRequestBody = {
file: http.file(binFile)
};
const response = http.post(url, postData);
check(response, {
'status is 200': r => r.status === 200,
});
sleep(1);
};
Now the next step is to convert the corresponding code to a .js (javascript) file using babel and webpack.
Creating .babelrc file
{
"presets": ["@babel/env", "@babel/typescript"],
"plugins": ["@babel/proposal-class-properties", "@babel/proposal-object-rest-spread"]
}
Creating webpack config file
const path = require('path');
const {
CleanWebpackPlugin
} = require('clean-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const GlobEntries = require('webpack-glob-entries');
module.exports = {
mode: 'production',
entry: GlobEntries('./src/*test*.ts'), // Generates multiple entry for each test
output: {
path: path.join(__dirname, 'dist'),
libraryTarget: 'commonjs',
filename: '[name].js',
},
resolve: {
extensions: ['.ts', '.js'],
},
module: {
rules: [{
test: /\.ts$/,
use: 'babel-loader',
exclude: /node_modules/,
}, ],
},
target: 'web',
externals: /^(k6|https?\:\/\/)(\/.*)?/,
// Generate map files for compiled scripts
devtool: "source-map",
stats: {
colors: true,
},
plugins: [
new CleanWebpackPlugin(),
// Copy assets to the destination folder
// see `src/post-file-test.ts` for an test example using an asset
new CopyPlugin({
patterns: [{
from: path.resolve(__dirname, 'assets'),
noErrorOnMissing: true
}],
}),
],
optimization: {
// Don't minimize, as it's not used in the browser
minimize: false,
},
};
Configuring package.json file
"scripts": {
"start": "webpack && k6 run dist/post-file-test.js"
}
Result
Once all the above steps are configured the output would showcase like below