Search code examples
javascripttestingasync-awaite2e-testingtestcafe

TestCafe: awaiting ClientFunction to resolve in expect method leads to unexpected behavior


I'm currently facing an issue where awaiting a TestCafe ClientFunction within a assertion query chain leads to the behavior demonstrated by the code below:

const getPageUrl = ClientFunction(() => window.location.href.toString());

// This test works fine
test("Test that works as expected", async t => {
  await t
    .click(pageElements.someNaviButton) // navigates me to the site with url extension /some/url
    .expect(getPageUrl()).contains("/some/url")
});

// This test works fine as well
test("Another test that works as expected", async t => {
  await t.click(pageElements.someNaviButton) // navigates me to the site with url extension /some/url
  const myPageUrl = await getWindowLocation();
  await t.expect(myPageUrl).contains("/some/url")
});

// This test fails
test("Test that does not work as expected", async t => {
  await t
    .click(pageElements.someNaviButton)
    .expect(await getPageUrl()).contains("/some/url")
});

According to TestCafe's documentation, one has to await asynchronous ClientFunctions. This leads me to what irritates me: I expect the second test to pass, which it does. Awaiting the method that encapsulates the ClientFunction within the expect method of the third test seems to be problematic, but why is that?

Additional info that could be of interest: I'm using TestCafe version 1.14.0.


Solution

  • Please consider that a test actions chain is a single expression. So, in the third test, getPageUrl is calculated before the chain execution. At that moment, the test is still on the start page. The first test passes because getPageUrl is calculated lazily via TestCafe Smart Assertion Query Mechanism. This is the most proper way to write this kind of tests. The second test passes because you broke the test actions chain.