Skip to content

Async Testing

James Adarich edited this page Aug 1, 2019 · 5 revisions

You can also have asynchronous tests simply by using the async keyword

import { Expect, Test, TestFixture } from "alsatian";

@TestFixture("Example Test Fixture")
export class ExampleTestFixture {

  @Test("async/await test")
  public async asyncTest() {
    const result = await somethingToHappen();
    Expect(result).toBe(1);
  }
}

If you for whatever reason can't use the async/await syntax you can return a promise instead and everything will work fine.

import { Expect, Test, TestFixture } from "alsatian";

@TestFixture("Example Test Fixture")
export class ExampleTestFixture {

  @Test("async promise test")
  public asyncTest() {

    return new Promise((resolve, reject) => {
      waitForSomethingToHappen((result: number) => {
         Expect(result).toBe(1);
         resolve();
      });
    });
  }
}

Alsatian will fail an async Test if it takes longer than 500 ms to execute. You can change this if you need to though using the Timeout decorators

import { Expect, Test, Timeout, TestFixture } from "alsatian";

@TestFixture("Example Test Fixture")
export class ExampleTestFixture {

  @Test("async test with different timeout")
  @Timeout(5000) // Alsatian will now wait 5 seconds before failing
  public async asyncTest() {
    const result = await somethingThatTakesAlmostFiveSeconds();
    Expect(result).toBe(1);
  }
}
Clone this wiki locally