Search code examples
node.jsangularprotractorimap

mail-listener2 - How to prevent function from reading wrong emails?


In my E2E test, I'am using the mail-listener2 to retrieve e-mails. It works fine, except one issue which is driving me crazy and just can't solve it... I have been searching and found different topics and issues regarding this library/package, but just couldn't really find the fix for that.

Following:

I use the function in more than one spec file (register, login, confirmation etc.), and this means that when retrieving the emails, I get from time to time the wrong one. In other words, the function reads the last e-mail in the Inbox which normally belongs to the first test.

Or sometimes the e-mail comes in the Inbox a little bit later that the function is reading them, so it reads the wrong one.

And as I do have an expectation in my it() function:

expect(email.subject).toEqual("subject for e-mail 1"); expect(email['headers'].to).toEqual( userEmail );

therefore the test breaks, and it get following error:

  - Expected 'user registration' to equal 'user confirmation'.
  - Failed: Cannot read property '1' of null

  - Expected 'john.doe@foo.de' to equal 'jane.doe@foo.com'.
  - Failed: Cannot read property '1' of null

Is there a way how to force the function reads just the specific email per subject and per user?


Solution

  • Yes, you can find this documented on node-imap (which is used by mail-listener2). Search for the paragraph/bullet on search within that package, here's a snippet to help you find it:

    For criteria types that require arguments, use an array instead of just the string criteria type name (e.g. ['FROM', 'foo@bar.com']).

    Below that, they list several other search criteria you can use, they have to/from for your user criteria, and subject for that one. So applying this to mail-listener2, you would use this in the searchFilter property:

    mailListener = new MailListener({
        ...(other options),
        searchFilter: [['FROM', 'automated@message.com'], ['SUBJECT', 'subject for e-mail 1']],
    });
    

    And if you need different search criteria for different tests, you can start a new mail-listener session for each test with the new searchFilter criteria.