Nightwatchjs Test Running Before the `before` Hook Completes
Asked 07 September, 2021
Viewed 1.3K times
  • 60
Votes

I have a nightwatchjs project setup with this code.

module.exports = {
    beforeEach: browser => {

        // Starts a new session for each test
        browser.refresh();
    },
    before: async browser => {

        // Get the encrypted token
        const { token } = await authorizeUser({ browser });

        // Create the Test Tool instance
        await initializeTestTool({
            browser,
            channelOriginId: CHANNEL_ORIGIN_ID,
            token,
        });
    },
    ...allTests.reduce((acc, test) => ({ ...acc, ...require(test) }), {})
};

The ...allTests.reduce part is adding more tests to the object. Here's the first test that runs.

module.exports = {
    'Verify Level 1 Taxonomies are Showing': browser => {

        // Specify the selector mode before using any selectors since the previous test could have changed the mode
        browser.useCss();

        // Wait for the frame to load
        browser.waitForElementVisible('iframe', RESPONSE_WAIT_TIME * 3);

        // Switch context to the iframe
        browser.frame(0);

        // Change selector mode to XPath. XPath allows selectors with text matching logic
        browser.useXpath();
        const qr0 = "//span[contains(text(), 'Something else')]";

        // Wait for the quick reply to be shown
        browser.waitForElementVisible(qr0, RESPONSE_WAIT_TIME);

        // Click the quick reply
        browser.click(qr0);
        const taxonomyResponse = `//div[contains(text(), '${l1TaxonomyResponse}')]`;

        // Make sure the chat bot gives the expected response
        browser.waitForElementVisible(taxonomyResponse, RESPONSE_WAIT_TIME);

        // Make sure all the level 1 taxonomy quick replies are displayed
        for (const quickReply of l1QuickReplies) {
            const quickReplyText = `//span[contains(text(), '${quickReply}')]`
            browser.waitForElementVisible(quickReplyText, RESPONSE_WAIT_TIME);
        }
    },
};

I am using this script to start the tests nightwatch automation.test.js -e chrome

The issue I'm running into is that the first test starts to run before the before hook completes. If it takes too long to complete then the first tests fails while waiting for an element to be shown. browser.waitForElementVisible('iframe', RESPONSE_WAIT_TIME * 3);

How can I force nightwatchjs to wait for the before hook to complete before running the automation tests?

0 Answer