Skip to content

MySQL Module

MySQL is the world's most popular open source database. With its proven performance, reliability and ease-of-use, MySQL has become the leading database choice for web-based applications, covering the entire range from personal projects and websites, via e-commerce and information services, all the way to high profile web properties including Facebook, Twitter, YouTube, Yahoo! and many more.

Install

npm install @testcontainers/mysql --save-dev

Examples

it("should connect and execute query", async () => {
  const container = await new MySqlContainer().start();

  const client = await createConnection({
    host: container.getHost(),
    port: container.getPort(),
    database: container.getDatabase(),
    user: container.getUsername(),
    password: container.getUserPassword(),
  });

  const [rows] = await client.execute("SELECT 1 as res");
  expect(rows).toEqual([{ res: 1 }]);

  await client.end();
  await container.stop();
});
it("should work with database URI", async () => {
  const username = "testUser";
  const password = "testPassword";
  const database = "testDB";

  // Test non-root user
  const container = await new MySqlContainer()
    .withUsername(username)
    .withUserPassword(password)
    .withDatabase(database)
    .start();
  expect(container.getConnectionUri()).toEqual(
    `mysql://${username}:${password}@${container.getHost()}:${container.getPort()}/${database}`
  );
  await container.stop();

  // Test root user
  const rootContainer = await new MySqlContainer().withRootPassword(password).withDatabase(database).start();
  expect(rootContainer.getConnectionUri(true)).toEqual(
    `mysql://root:${password}@${rootContainer.getHost()}:${rootContainer.getPort()}/${database}`
  );
  await rootContainer.stop();
});
it("should set username", async () => {
  const container = await new MySqlContainer().withUsername("customUsername").start();

  const client = await createConnection({
    host: container.getHost(),
    port: container.getPort(),
    database: container.getDatabase(),
    user: container.getUsername(),
    password: container.getUserPassword(),
  });

  const [rows] = await client.execute("SELECT CURRENT_USER() as res");
  expect(rows).toEqual([{ res: "customUsername@%" }]);

  await client.end();
  await container.stop();
});
it("should execute a query and return the result", async () => {
  const container = await new MySqlContainer().start();

  const queryResult = await container.executeQuery("SELECT 1 as res");
  expect(queryResult).toEqual(expect.stringContaining("res\n1\n"));

  await container.stop();
});