Escenarios de usuarios virtuales (VUs)
Defina y gestione diversos escenarios de usuarios virtuales para simular eficazmente distintos patrones de carga.
Escenarios de usuarios virtuales (VUs) es una lección gratuita de Load Testing & Performance Benchmarking (JMeter & k6) en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Load Testing & Performance Benchmarking (JMeter & k6), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Load Testing & Performance Benchmarking (JMeter & k6) incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Beyond Simple Load: k6 Scenarios
When performance testing, a simple 'run 10 VUs for 30 seconds' might not capture real user behavior. Real users often have different patterns: some log in, some browse, some make purchases. This is where k6 scenarios come in!
Scenarios allow you to define complex load profiles and simulate diverse user groups, each with its own specific behavior and load pattern, all within a single test script.
Defining Your Test Scenarios
In k6, you define scenarios within the options object of your test script. The scenarios block is a JavaScript object where each key represents a unique scenario name.
Each scenario specifies an executor, which dictates how virtual users (VUs) and iterations are managed. It also links to a specific function in your script that defines what those VUs will do.
import http from 'k6/http';
import { sleep } from 'k6';
export const options = {
scenarios: {
// Scenario definitions go here
},
};
export default function () {
http.get('https://test.k6.io');
sleep(1);
}Basic Scenario: Shared Iterations
The default k6 executor, shared-iterations, distributes a fixed number of iterations among a pool of VUs. Each VU will execute as many iterations as it can until the total specified iterations are complete or the test duration ends.
It's good for tests where you want to complete a specific amount of work.
import http from 'k6/http';
import { sleep } from 'k6';
export const options = {
scenarios: {
my_scenario: {
executor: 'shared-iterations',
vus: 5,
iterations: 20,
maxDuration: '30s',
},
},
};
export default function () {
http.get('https://test.k6.io');
sleep(1);
}Constant Load with `constant-VUs`
The constant-VUs executor maintains a fixed number of virtual users throughout the test's duration. VUs are started at the beginning and kept active until the duration is met.
This is useful for simulating a steady, continuous load on your system.
import http from 'k6/http';
import { sleep } from 'k6';
export const options = {
scenarios: {
constant_load: {
executor: 'constant-VUs',
vus: 10,
duration: '1m', // Run 10 VUs for 1 minute
},
},
};
export default function () {
http.get('https://test.k6.io/news.php');
sleep(2);
}Gradual Load with `ramping-VUs`
The ramping-VUs executor allows you to gradually increase or decrease the number of virtual users over time. This simulates a more realistic load curve, like users slowly joining a website or leaving it.
It uses stages to define these changes in VU count.
import http from 'k6/http';
import { sleep } from 'k6';
export const options = {
scenarios: {
gradual_load: {
executor: 'ramping-VUs',
startVUs: 0,
stages: [
{ duration: '30s', target: 20 }, // Ramp up to 20 VUs over 30s
{ duration: '1m', target: 20 }, // Stay at 20 VUs for 1 minute
{ duration: '20s', target: 0 }, // Ramp down to 0 VUs over 20s
],
},
},
};
export default function () {
http.get('https://test.k6.io/contacts.php');
sleep(1);
}Structuring Load with Stages
Within ramping-VUs, stages are an array of objects, each with a duration and a target VU count.
duration: How long this stage lasts (e.g., '1m', '30s').target: The number of VUs to reach by the end of this stage. k6 will linearly ramp VUs from the current stage's end target to the next stage's target.
Stages are powerful for modeling complex load patterns like peak hours or sudden traffic spikes.
Controlling Request Rate: `ramping-arrival-rate`
Unlike VU-based executors, ramping-arrival-rate is an open model executor. It controls the rate at which new iterations (or 'arrivals') are started, rather than the number of VUs.
This is ideal for testing systems where you care about requests per second (RPS) or transactions per second (TPS).
import http from 'k6/http';
import { sleep } from 'k6';
export const options = {
scenarios: {
arrival_rate_test: {
executor: 'ramping-arrival-rate',
startRate: 0, // Initial iterations per second
timeUnit: '1s', // How often 'rate' is applied
stages: [
{ duration: '30s', target: 10 }, // Ramp up to 10 iterations/s over 30s
{ duration: '1m', target: 10 }, // Stay at 10 iterations/s for 1 minute
],
preAllocatedVUs: 20, // Initial VUs to allocate
maxVUs: 50, // Max VUs to spin up if needed
},
},
};
export default function () {
http.get('https://test.k6.io/login.php');
sleep(0.5); // Simulate some user think time
}Combining Different User Behaviors
You can define multiple, independent scenarios within a single k6 script. Each scenario can have its own executor, VUs, duration, and even call a different function that defines its specific user journey.
This allows you to simulate a mix of user types (e.g., admin users, regular users, guests) in one comprehensive test.
import http from 'k6/http';
import { sleep } from 'k6';
export const options = {
scenarios: {
anonymous_browsing: {
executor: 'constant-VUs',
vus: 5,
duration: '30s',
exec: 'anonymousBrowser', // Call this function
},
authenticated_user: {
executor: 'ramping-VUs',
startVUs: 0,
stages: [{ duration: '20s', target: 3 }],
exec: 'loggedInUser', // Call this function
},
},
};
export function anonymousBrowser() {
http.get('https://test.k6.io/');
sleep(2);
}
export function loggedInUser() {
// Simulate login (not actual login, just for demo)
http.post('https://test.k6.io/login', { username: 'user', password: 'pass' });
sleep(1);
http.get('https://test.k6.io/my-profile');
sleep(2);
}Fine-Tuning Scenario Execution
Beyond basic executor settings, scenarios offer additional options for precise control:
startTime: Delay the start of a specific scenario (e.g., '10s' after test start). Useful for staggered tests.gracefulStop: How long k6 should wait for active VUs to finish their current iteration before forcefully stopping them (e.g., '5s').env: Environment variables specific to this scenario.
These options help orchestrate complex test flows.
Scenario Challenge
You need to simulate a load test where:
- 5 virtual users (VUs) constantly browse the homepage for 1 minute.
- At the same time, another group of users gradually ramps up from 0 to 10 VUs over 30 seconds, then holds at 10 VUs for 30 seconds, performing a login action.
Which two k6 executors would be most appropriate for these two distinct user behaviors?
Scenarios: Your Load Orchestrator
In this lesson, you've learned how k6 scenarios enable you to model diverse and realistic load patterns. We explored key executors:
shared-iterationsfor fixed work.constant-VUsfor steady load.ramping-VUsfor gradual load changes with stages.ramping-arrival-ratefor open-model testing based on request rate.
You also saw how to combine multiple scenarios and use options like startTime for advanced control. Mastering scenarios is crucial for sophisticated performance testing!
Preguntas frecuentes
¿La lección «Escenarios de usuarios virtuales (VUs)» es gratis?
Sí — el texto completo de «Escenarios de usuarios virtuales (VUs)» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Load Testing & Performance Benchmarking (JMeter & k6), actualiza a CoddyKit PRO. El curso de Load Testing & Performance Benchmarking (JMeter & k6) incluye 4 lecciones en total.
¿Qué aprenderé en «Escenarios de usuarios virtuales (VUs)»?
Defina y gestione diversos escenarios de usuarios virtuales para simular eficazmente distintos patrones de carga. Practicas Load Testing & Performance Benchmarking (JMeter & k6) con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Load Testing & Performance Benchmarking (JMeter & k6)?
No se requiere experiencia previa. Load Testing & Performance Benchmarking (JMeter & k6) en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.
¿Cuánto tiempo toma la lección «Escenarios de usuarios virtuales (VUs)»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Load Testing & Performance Benchmarking (JMeter & k6)?
Sí. Cada lección de Load Testing & Performance Benchmarking (JMeter & k6) incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Escenarios de usuarios virtuales (VUs)
- Parametrización de datos en k6
- Ejecución de k6 en la nube
- Métricas personalizadas y tendencias en k6