0Pricing
Load Testing & Performance Benchmarking (JMeter & k6) · 课时

编写基础 k6 脚本

创建您的第一个 k6 脚本,发送 HTTP 请求并模拟虚拟用户

编写基础 k6 脚本 是 CoddyKit 上的免费 Load Testing & Performance Benchmarking (JMeter & k6) 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Load Testing & Performance Benchmarking (JMeter & k6) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Load Testing & Performance Benchmarking (JMeter & k6) 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Start Your k6 Script Journey

Welcome to writing k6 scripts! k6 uses JavaScript to define your load tests, making it familiar for many developers.

A k6 script describes what your virtual users will do and how the load should be simulated.

  • Define user actions like visiting pages or logging in.
  • Specify the number of virtual users (VUs) and test duration.
  • Validate server responses to ensure correctness.

Anatomy of a k6 Script

Every k6 script typically has two main parts:

  • The options object: Here you configure test-wide settings like virtual users (VUs) and test duration.
  • The default function: This is where your virtual users' actions are defined. It's executed repeatedly by each VU.

Think of the default function as the "main loop" for each virtual user.

Sending HTTP GET Requests

The most common action in a performance test is sending an HTTP request. k6 provides the k6/http module for this.

To send a simple GET request, you'll use http.get('URL'). This simulates a browser fetching a web page or an API endpoint.

Remember to import the http module at the top of your script.

Code: Basic GET Request

Let's write our first k6 script to make a GET request to example.com. Copy and run this script using the k6 CLI.

k6 run your_script.js

import http from 'k6/http';
import { sleep } from 'k6/execution';

export default function () {
  http.get('https://test.k6.io');
  sleep(1); // Wait for 1 second between requests
}

What are Virtual Users (VUs)?

In k6, a Virtual User (VU) simulates a real user interacting with your system. Each VU executes the default function independently.

If you have 10 VUs, it's like 10 people simultaneously using your application. k6 efficiently manages these VUs.

By controlling the number of VUs, you can simulate different levels of load on your application.

Configuring Test Load with Options

The options object is crucial for defining your test scenario. It sits at the top level of your script.

Two key options are:

  • vus: The total number of virtual users to run concurrently.
  • duration: How long the test should run (e.g., '30s', '5m', '2h').

These settings tell k6 how to distribute and execute your default function.

Code: VUs and Test Duration

This script runs with 5 virtual users for a duration of 10 seconds, hitting the test website repeatedly.

Observe how k6 reports the VUs and duration when you run this script.

import http from 'k6/http';
import { sleep } from 'k6/execution';

export const options = {
  vus: 5,
  duration: '10s',
};

export default function () {
  http.get('https://test.k6.io');
  sleep(1);
}

Sending Data with POST Requests

Beyond GET, you often need to send data to the server, like submitting a form or creating a resource. For this, you use http.post().

The http.post() function takes three arguments:

  • The URL.
  • The request body (usually a JSON string or form data).
  • Optional parameters like headers.

Code: Simple POST Request

Here's an example of a POST request sending JSON data. Notice how we specify the Content-Type header to tell the server we're sending JSON.

import http from 'k6/http';
import { sleep } from 'k6/execution';

export const options = {
  vus: 1,
  duration: '5s',
};

export default function () {
  const url = 'https://httpbin.org/post';
  const payload = JSON.stringify({
    name: 'Coddy',
    job: 'Learner',
  });

  const params = {
    headers: {
      'Content-Type': 'application/json',
    },
  };

  http.post(url, payload, params);
  sleep(1);
}

Test Your Scripting Skills

Which of the following statements about basic k6 scripting are TRUE?

Recap: Your First k6 Scripts

Great job! You've learned the fundamentals of writing k6 scripts:

  • The basic structure with options and the default function.
  • How to send simple HTTP GET and POST requests using k6/http.
  • Configuring test load with vus and duration.

In the next lesson, we'll dive into validating responses with Checks and setting performance targets with Thresholds!

常见问题解答

「编写基础 k6 脚本」课时是免费的吗?

是的 — 「编写基础 k6 脚本」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Load Testing & Performance Benchmarking (JMeter & k6) 课程的其余内容,请升级到 CoddyKit PRO。 Load Testing & Performance Benchmarking (JMeter & k6) 课程共包含 4 节课。

「编写基础 k6 脚本」这节课中我会学到什么?

创建您的第一个 k6 脚本,发送 HTTP 请求并模拟虚拟用户 你通过在浏览器中直接运行的动手代码来练习 Load Testing & Performance Benchmarking (JMeter & k6),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Load Testing & Performance Benchmarking (JMeter & k6) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Load Testing & Performance Benchmarking (JMeter & k6) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「编写基础 k6 脚本」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Load Testing & Performance Benchmarking (JMeter & k6) 课中编写并运行代码吗?

能。每节 Load Testing & Performance Benchmarking (JMeter & k6) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 安装 k6 与使用 CLI
  2. 编写基础 k6 脚本
  3. 检查、阈值与指标
  4. 使用组和标签组织测试
← 返回 Load Testing & Performance Benchmarking (JMeter & k6)