lecture 5 of 220 completed

Your first test

The anatomy of a test: build, get, act, assert, quit. And what makes it a real test.

What you'll learn

  • The shape of a Selenium script, start to finish
  • How to name a test so a failure explains itself
  • Why a test without a check proves nothing

A Selenium test has a shape you will write hundreds of times. Here it is, testing Nimbus, the login page you met in the last lecture:

const { Builder, By, until } = require('selenium-webdriver');
const assert = require('assert');

describe('Nimbus login', function () {
  it('shows validation errors for an empty form', async function () {
    const driver = await new Builder().forBrowser('chrome').build();
    await driver.get('/');
    await driver.findElement(By.css('[data-testid="login-button"]')).click();

    const emailError = await driver.wait(
      until.elementLocated(By.css('[data-testid="email-error"]')),
      5000
    );
    assert.ok(await emailError.isDisplayed());
    await driver.quit();
  });
});

Read it as five layers:

  1. describe / it come from the test runner (Mocha here). it is one test, and its name is a claim about the app, "shows validation errors for an empty form" tells a reader exactly what broke when it fails.
  2. Setup: build() starts the browser, get('/') loads the page.
  3. Act like a user: find the Sign in button, click it.
  4. Wait, then assert. driver.wait(until.elementLocated(...), 5000) polls until the error message exists (up to 5 seconds), then assert.ok(...) states what must be true. The assert is the test. Without it, the code runs, clicks, finishes, and passes whether the app works or not.
  5. Teardown: quit() ends the session. Always.

That fourth point is the difference between code that runs and a test that proves something. A test with no check passes against a completely broken app.

A test file can contain fourteen tests, every one clicking through a form and finishing, with no checks anywhere. The suite is green. It has never tested anything.

When you solve problems here, we check this for real: we break the app on purpose, and your test must turn red.

The official first-script guide: Your first Selenium script.

Now prove it: write this exact test yourself in the problem below, and we will check it catches the bug.

now prove it

Reading is the setup. Solve this problem in the editor. We break the app on purpose to check your test would catch it.