Skip to main content

_javascript

TL;DR - Show Me The Code

1-upload-a-file/code/javascript/test/upload.spec.js
const assert = require("assert");
const {Builder, By} = require("selenium-webdriver");
const path = require("path");

describe("Upload Test", function () {
let driver;

beforeEach(async function () {
driver = await new Builder().forBrowser("firefox").build();
});

afterEach(async function () {
await driver.quit();
});

it("upload a file", async function () {
let filename = "some-file.txt";
let filePath = path.join(process.cwd(), filename);

await driver.get("https://the-internet.herokuapp.com/upload");
await driver.findElement(By.id("file-upload")).sendKeys(filePath);
await driver.findElement(By.id("file-submit")).click();

let text = await driver.findElement(By.id("uploaded-files")).getText();
assert.equal(text, filename);
});
});

Code Walkthrough

Importing Libraries

Lines 1 to 3 are pulling in our requisite classes for interacting with the operating system (e.g., require("path");), our testing framework (e.g., mocha and require("assert")), and driving the browser with Selenium (e.g., const {Builder, By} = require("selenium-webdriver");).

Setup and Teardown

After creating a describe to group our tests (e.g., describe("Upload Test")...), lines 8 to 14 are setting up and tearing down the browser instance.

The beforeEach method, will execute before each test. In it, we are launching a new instance of Firefox with Selenium and storing it in a class variable that we'll use throughout all tests. After our test executes the second method, afterEach, will execute. This calls driver.quit() which ends the session by closing the browser instance.

The Test

Lines 17 to 25 are the test itself.

After declaring the test method (e.g., it("upload a file")...) we specify the name of file we'd like to upload. It's a text file called some-file.txt in the current working directory. We determine the path to this file and store it in a variable called filePath.

Next we visit the page with the upload form, input the string value of filePath, and click the submit button on the form. After the file is uploaded to the page it will display the filename it just processed. We use this text on the page to perform our assertion (making sure the uploaded file is what we expect).

Executing the Test

Before executing the test, we need to make sure the required dependencies are declared on the package.json file.

Toggle to see the package.json file.
1-upload-a-file/code/javascript/package.json
{
"dependencies": {
"selenium-webdriver": "4.26.0"
},
"description": "A project to showcase uploading a file using official WebdriverJs",
"devDependencies": {
"mocha": "10.8.2"
},
"license": "MIT",
"name": "upload-a-file",
"scripts": {
"test": "npx mocha test/**/*.spec.js --timeout 60000"
},
"version": "1.0.0"
}

Finally, we can run the test by executing npm test from the command-line.