Protractor Print for Beginners: Accurate Testing Guide

· Admin · 917 words

When diving into automated end-to-end (E2E) testing for Angular and JavaScript applications, seeing what your test is doing at any given second is essential. For newcomers, however, printing out values, element texts, or browser errors often produces bewildering output like ManagedPromise::123 {[[PromiseStatus]]: "pending"} instead of the expected string. Navigating Protractor Print for Beginners: Unlock the Secrets of Accurate Testing is about mastering how asynchronous JavaScript interacts with your test runner so you can inspect data reliably, isolate failures instantly, and build resilient test suites.

Printable Protractor 360 Pdf
Source: ar.inspiredpencil.com

Why Printing in Protractor Is Different from Standard JavaScript

In standard Node.js scripts, printing a value to the terminal is as simple as calling console.log(myVariable). In Protractor, virtually every interaction with the browser—such as finding an element, clicking a button, or retrieving text—is an asynchronous operation powered by WebDriverJS.

When you call a method like element(by.css('.status-message')).getText(), Protractor does not immediately return a string. Instead, it returns a Promise. If you pass that Promise directly to console.log(), the runtime prints the promise wrapper object rather than the resolved text inside the DOM node. To perform accurate testing, you must understand how to resolve these promises before attempting to print or assert their values.

Protractor Print for Beginners: Unlock the Secrets of Accurate Testing

To inspect values accurately during test execution, you must resolve promises using either modern async/await syntax or legacy .then() callback chains. Modern Protractor configurations prioritize async/await because it makes asynchronous code look and behave like synchronous code.

1. Printing Element Text Using Async/Await

Using async/await is the cleanest and most readable way to print element attributes, values, and inner text in Protractor. Disable the WebDriver Control Flow in your configuration file (SELENIUM_PROMISE_MANAGER: false) and declare your test functions with the async keyword:

it('should print the user dashboard header', async () => {
  await browser.get('https://example.com/dashboard');
  
  const headerElement = element(by.css('h1.dashboard-title'));
  const headerText = await headerElement.getText();
  
  console.log('Current Dashboard Header:', headerText);
  expect(headerText).toEqual('Welcome Back, Admin');
});

2. Printing Values Using the Promise Chain (.then)

If you are working with an older codebase where Control Flow is enabled or async/await is not yet adopted, you can resolve the promise explicitly using .then():

it('should print the item count using .then()', () => {
  browser.get('https://example.com/inventory');
  
  element(by.id('item-count')).getText().then((text) => {
    console.log('Total items found:', text);
    expect(text).toContain('42 items');
  });
});

Capturing and Printing Browser Console Logs

Video: ANGLE-IZER® Square Head Stainless Steel Angle Protractor, 0 to 180 Degrees, 6-Inch Arm

Printable Protractor Download at Richard Harvey blog
Source: storage.googleapis.com

Often, accurate testing requires looking beyond visible DOM elements. Client-side JavaScript errors, failed API calls, and missing resources frequently trigger silent test failures. Protractor allows you to extract and print the browser's internal console logs directly to your terminal.

You can fetch these logs using browser.manage().logs().get('browser'). Here is how to inspect browser-level issues during a test run:

afterEach(async () => {
  const browserLogs = await browser.manage().logs().get('browser');
  
  if (browserLogs.length > 0) {
    console.log('\n--- Browser Console Messages ---');
    browserLogs.forEach((entry) => {
      console.log(`[${entry.level.name}] ${entry.message}`);
    });
    console.log('---------------------------------\n');
  }
});

This approach ensures that if a component crashes or an uncaught exception occurs in the client runtime, the stack trace prints straight into your test output, cutting down investigation time from hours to seconds.

Printing Multi-Element Lists and Repeater Data

A frequent challenge for beginners is extracting and printing data from repeating elements, such as tables or lists generated by Angular's *ngFor. Using element.all() returns an ElementArrayFinder, which requires specific methods to iterate through and display values cleanly.

Using map() to Print All Items

The map() method iterates over each element in an array finder, resolves the inner promises, and returns an array of resolved values:

it('should print all navigation menu links', async () => {
  await browser.get('https://example.com');
  
  const navLinks = await element.all(by.css('nav ul li a')).map(async (elem) => {
    return await elem.getText();
  });
  
  console.log('Navigation links present:', navLinks);
  expect(navLinks).toContain('Pricing');
});

Best Practices for Accurate Printing in Automated Tests

While printing is invaluable for local debugging, unmanaged log statements can clutter output and slow down test execution. Apply these guidelines to maintain clean, professional test suites:

  • Do not substitute prints for assertions: A test should never rely on human review of terminal output to pass or fail. Always follow your print statements with explicit expect() matchers.
  • Prefix your log outputs: Add recognizable prefixes like [DEBUG] or [TEST DATA] to your log strings. This makes grep filtering easier in automated CI/CD logs.
  • Clean up temporary logs before merging: Remove ad-hoc console.log() statements used during feature development. Retain only structured logs that provide diagnostic value upon test failure.
  • Use ExpectedConditions before printing: If you try to print an element's text before it has finished rendering, Protractor will throw a NoSuchElementError. Use browser.wait(EC.visibilityOf(element), 5000) to ensure elements are mounted before reading them.

Summary: Building Confidence in Your Test Results

Printing is often the first tool developers reach for when diagnosing a broken automated test. By understanding how Protractor handles asynchronous promises, utilizing async/await syntax, and tapping into browser-level logs, you eliminate guesswork from your test suite. Accurate logging turns opaque automated failures into clear, actionable data points, ensuring your end-to-end tests remain dependable assets in your continuous delivery pipeline.

Image Gallery

Protractor Automated Testing JavaScript Selenium QA Testing Web Development