Search code examples
react-nativetestinge2e-testingdetox

How to add negative assertions like not.toHaveText in Detox?


I need to set negation for some text content and tried the code below but as it isn't stated in the docs I expected it to fail and it sure did, so I would like to know how could I possibly achieve negation in this case.

await expect(element(by.id('myElemId'))).not.toHaveText('some text')


Solution

  • Unfortunately I don' think Detox has the ability to use the .not property of expect

    However you could so something like this:

    First create a function that returns a boolean if a specific text phrase exists. We use the fact that if a value doesn't exist it will throw and error, by wrapping it in a try/catch we can return a boolean that we can then use in our tests.

    async function hasText (id, text) {
      try {
        await expect(element(by.id(id))).toHaveText(text);
        return true;
      } catch (err) {
        return false;
      }
    }
    

    You can then use it in the following way throwing an error if it returns true for having the text.

    it('should not have some text', async () => {
      await expect(element(by.id('myElemId'))).toBeVisible();
      let result = await hasText('myElemId', 'some text');
      // so if the text exists it will return true, as we don't want it to exist then we can throw our own error.
      if (result) {
        throw new Error('Should not have some text, but did.');
      }
    });
    

    I know that this is not an elegant solution to the problem, and it would be much nicer if Detox gave us the APIs we needed but I suppose that this could be used in a pinch.