CodeWithMMAK
Test AutomationIntermediate

Writing Your First Protractor Test with TypeScript: A Step-by-Step Guide

Learn how to write, compile, and execute your first automated test in Protractor using TypeScript and Jasmine. Perfect for beginners entering the Angular testing world.

CodeWithMMAK
November 25, 2018
8 min

Introduction

🎯 Quick Answer

To write your first Protractor test with TypeScript:

  1. Create a .spec.ts file in a specs folder.
  2. Use describe and it blocks from Jasmine.
  3. Use the browser object to navigate and interact with the page.
  4. Create a conf.ts file to define your test settings.
  5. Compile your TypeScript code using tsc and run it using the protractor command.

Writing your first test is the most exciting part of learning a new automation tool. By using TypeScript with Protractor, you're setting yourself up for success with better code quality and a smoother development experience.

📖 Key Definitions

Spec File

A file containing your test cases, usually ending in .spec.ts or .test.ts.

describe

A Jasmine function used to group related tests together into a "test suite."

it

A Jasmine function that defines a single "test case" or "spec."

browser.get()

A Protractor command used to navigate to a specific URL in the browser.

🚀 Step-by-Step Implementation

1

Create Project Structure

Open Visual Studio Code and create a new folder named specs. This is where all your test files will reside.

2

Create Your First Spec

Inside the specs folder, create a file named first.spec.ts.

3

Write the Test Code

Add the following code to first.spec.ts:

Code Snippet
import { browser } from 'protractor';

describe('Protractor and TypeScript Demo', () => {
    it('should verify the page title', async () => {
        await browser.get('https://angularjs.org/');
        const title = await browser.getTitle();
        console.log("The page title is: " + title);
        expect(title).toContain('AngularJS');
    });
});
4

Configure the Test Runner

In the root folder, create a conf.ts file:

Code Snippet
import { Config, browser } from 'protractor';

export let config: Config = {
    directConnect: true,
    capabilities: { 'browserName': 'chrome' },
    framework: 'jasmine',
    specs: ['./specs/*.spec.js'], // Point to compiled JS
    onPrepare: () => {
        browser.manage().window().maximize();
    }
};
5

Compile and Run

Run tsc to compile your TypeScript files, then execute the test:

Code Snippet
protractor conf.js

Common Errors & Best Practices

⚠️ Common Errors & Pitfalls

  • Promise Not Resolved

    Forgetting to use await with Protractor commands. This results in the test finishing before the browser actions are complete.

  • Incorrect Spec Path

    If your conf.js points to the wrong folder for your compiled .js files, Protractor will report "0 specs found."

  • Angular Synchronization Failure

    If the page takes too long to load, Protractor might timeout. You may need to increase the allScriptsTimeout in your config.

Best Practices

  • Always use async/await for all Protractor commands to ensure synchronous-like execution flow.
  • Use Assertions (expect) to verify your test results rather than just logging them to the console.
  • Keep your Config File clean and use onPrepare for global setup tasks like window maximization.
  • Organize your tests into Folders based on features or modules to keep your project scalable.

Frequently Asked Questions

Do I need to start a Selenium server?

No, if you use directConnect: true in your config, Protractor will talk directly to the browser driver.

Can I use other browsers?

Yes, you can change the browserName to firefox or internet explorer in the capabilities section of your config.

How do I debug my tests?

You can use browser.pause() to stop execution and inspect the browser state, or use VS Code's built-in debugger.

Conclusion

Writing your first Protractor test with TypeScript is a significant milestone. By mastering the basic structure of specs and configurations, you've laid the groundwork for building a comprehensive automation suite that can handle complex user workflows with ease.

📝 Summary & Key Takeaways

This tutorial provided a comprehensive walkthrough for writing and executing a first automated test using Protractor and TypeScript. We covered the creation of a structured project directory, the implementation of a basic test suite using Jasmine's describe and it blocks, and the configuration of the Protractor runner. Key emphasis was placed on using modern async/await syntax for handling asynchronous browser operations and the importance of a proper compilation step from TypeScript to JavaScript. By following these steps and adhering to best practices like using assertions and organized project structures, beginners can successfully transition into building robust end-to-end testing frameworks for modern web applications.

Share it with your network and help others learn too!

Follow me on social media for more developer tips, tricks, and tutorials. Let's connect and build something great together!