기본 k6 스크립트 작성
첫 번째 k6 스크립트를 작성하여 HTTP 요청을 보내고 가상 사용자를 시뮬레이션합니다.
기본 k6 스크립트 작성은(는) CoddyKit의 무료 Load Testing & Performance Benchmarking (JMeter & k6) 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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
optionsobject: Here you configure test-wide settings like virtual users (VUs) and test duration. - The
defaultfunction: 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
optionsand thedefaultfunction. - How to send simple HTTP GET and POST requests using
k6/http. - Configuring test load with
vusandduration.
In the next lesson, we'll dive into validating responses with Checks and setting performance targets with Thresholds!
자주 묻는 질문
“기본 k6 스크립트 작성” 강의는 무료인가요?
네 — “기본 k6 스크립트 작성” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Load Testing & Performance Benchmarking (JMeter & k6) 강의 전체를 잠금 해제할 수 있습니다. Load Testing & Performance Benchmarking (JMeter & k6) 강의에는 총 4개의 강의가 포함되어 있습니다.
“기본 k6 스크립트 작성”에서 뭘 배우나요?
첫 번째 k6 스크립트를 작성하여 HTTP 요청을 보내고 가상 사용자를 시뮬레이션합니다. 브라우저에서 직접 실행하는 실습 코드로 Load Testing & Performance Benchmarking (JMeter & k6)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Load Testing & Performance Benchmarking (JMeter & k6)을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Load Testing & Performance Benchmarking (JMeter & k6)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“기본 k6 스크립트 작성” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Load Testing & Performance Benchmarking (JMeter & k6) 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Load Testing & Performance Benchmarking (JMeter & k6) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- k6 설치 및 CLI
- 기본 k6 스크립트 작성
- 검사, 임계값 및 메트릭
- 시험 구성을 위한 그룹 및 태그