1

I want to create tests in my repo (https://github.com/DWboutin/jest-spectron-ts) all seems to work, but I can't access the Application.client API in my tests.

I tried in Promises style, async/await, with Mocha and I can't make it work.

This is my only test file (very basic)


const path = require("path");
const Application = require("spectron").Application;
const electron = require("electron");

jest.setTimeout(10000); // increase to 50000 on low spec laptop

let app: any = new Application({
  path: electron,
  args: [path.join(__dirname, "..", ".webpack", "main", "index.js")]
});

describe("test", () => {
  beforeAll(async () => {
    await app.start();
  });

  afterAll(async () => {
    if (app && app.isRunning()) {
      await app.stop();
    }
  });

  it("shows an initial window", async () => {
    const windowCount = await app.client.getWindowCount();

    expect(windowCount).toBe(1); // this gives 2, I don't know why
  });

  it("should have correct text", async () => {
    const h1Text = await app.client.getText("h1"); // TypeError: app.client.getText is not a function

    expect(h1Text).toEqual("Hello World!");
  });
});

Can someone help me please?

Mike Boutin
  • 5,015
  • 11
  • 34
  • 63

1 Answers1

2

In regards to your comment about windowCount being 2, see the last comment in this section of the docs.

// Please note that getWindowCount() will return 2 if dev tools are opened.

I don't know if devtools are open or not, but that seems to be the official reasoning for now.

In regards to app.client.getText not being a function, it is because it is not a function. It actually seems the documentation is incorrect - possibly not updated from v11.0.0 to v11.1.0, and forgotten about.

Spectron uses WebdriverIO and exposes the managed client property on the created Application instances. The client API is WebdriverIO's browser object.

Source: https://github.com/electron-userland/spectron#client

The browser object for WebdriverIO does not contain a getText function (https://webdriver.io/docs/api.html), however, an element retrieved does have the getText function in question.

This should solve your problem:

it("should have correct text", async () => {
  // because there are "two" windows...
  await app.client.windowByIndex(1);
  // use query selector to get h1
  const header = await app.client.$("h1");
  // grab the text from the element
  const h1Text = await header.getText();

  expect(h1Text).toEqual(" Hello World!");
});

This unit test on the spectron repository pointed me in the right direction for this solution.

Cheers.

J. Titus
  • 8,230
  • 1
  • 27
  • 40