0Pricing
Blockchain Smart Contracts with Solidity · Lección

Escritura y ejecución de pruebas de contratos

Escriba pruebas automatizadas para sus smart contracts y detecte errores antes de desplegarlos en una red activa.

Escritura y ejecución de pruebas de contratos es una lección gratuita de Blockchain Smart Contracts with Solidity en CoddyKit. Esta es la lección 4 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 Blockchain Smart Contracts with Solidity, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Blockchain Smart Contracts with Solidity incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Why Test Smart Contracts?

Deployed contract code is immutable and often holds real value. A bug can be unfixable and costly. Automated tests let you verify behavior repeatedly and safely before any deployment.

The Test Toolkit

Hardhat and Truffle integrate test runners. Hardhat commonly uses Mocha with the Chai assertion library and ethers.js to deploy and call contracts in tests.

Test File Layout

Tests live in the test/ folder. Each file describes a contract with describe blocks and individual cases with it blocks.

describe("Counter", function () {
  it("starts at zero", async function () {
    // ...
  });
});

Deploying in a Test

Before each test you deploy a fresh contract instance so tests stay isolated and do not affect each other.

const Counter = await ethers.getContractFactory("Counter");
const counter = await Counter.deploy();

Making Assertions

Call a contract function and assert the result with Chai. Reading the returned value confirms the contract behaves as expected.

expect(await counter.value()).to.equal(0);
await counter.increment();
expect(await counter.value()).to.equal(1);

Testing Reverts

Good tests also confirm failures. Assert that a call reverts with the expected reason when given invalid input.

await expect(counter.setOwner(addr)).to.be.revertedWith("Not owner");

Testing Events

Verify that a function emits the right event with the right arguments. Events are how off-chain apps learn about state changes.

await expect(counter.increment())
  .to.emit(counter, "Incremented")
  .withArgs(1);

Working with Multiple Accounts

Test access control by calling functions from different signers. Connect a contract to another account to simulate a non-owner trying a restricted action.

const [owner, other] = await ethers.getSigners();
await expect(counter.connect(other).reset())
  .to.be.reverted;

Manipulating Time and State

Test runners can fast-forward block time and mine blocks, letting you test time-locked logic without waiting. This is essential for vesting or auction contracts.

Measuring Coverage

A coverage tool reports which lines and branches your tests exercise. Aim for high coverage on critical paths, especially money-moving functions and access checks.

npx hardhat coverage

Running the Suite

Run all tests with a single command. Integrate this into CI so every change is verified automatically before merge or deploy.

npx hardhat test

Quick Check

Check your contract testing knowledge.

Recap

You learned to test contracts:

  • Use Mocha/Chai with ethers in the test/ folder
  • Deploy a fresh instance and assert return values
  • Test reverts, events, and multiple accounts
  • Manipulate time, measure coverage, and run in CI

A solid test suite is your best defense against costly on-chain bugs.

Preguntas frecuentes

¿La lección «Escritura y ejecución de pruebas de contratos» es gratis?

Sí — el texto completo de «Escritura y ejecución de pruebas de contratos» 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 Blockchain Smart Contracts with Solidity, actualiza a CoddyKit PRO. El curso de Blockchain Smart Contracts with Solidity incluye 4 lecciones en total.

¿Qué aprenderé en «Escritura y ejecución de pruebas de contratos»?

Escriba pruebas automatizadas para sus smart contracts y detecte errores antes de desplegarlos en una red activa. Practicas Blockchain Smart Contracts with Solidity 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 Blockchain Smart Contracts with Solidity?

No se requiere experiencia previa. Blockchain Smart Contracts with Solidity 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 4 de 4.

¿Cuánto tiempo toma la lección «Escritura y ejecución de pruebas de contratos»?

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 Blockchain Smart Contracts with Solidity?

Sí. Cada lección de Blockchain Smart Contracts with Solidity 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

  1. Configuración de Hardhat o Truffle
  2. Compilación y despliegue de contratos
  3. Interacción con contratos desplegados
  4. Escritura y ejecución de pruebas de contratos
← Volver a Blockchain Smart Contracts with Solidity