0

For example I got this email function that is run every time I update the object to some state. It's asynchronous and in production I don't want to wait for the command of send the email to finish to just continue with the script.

But in the TESTS I really want very much to run the code synchronously so I could check that the email was sent too. Or just that the whole process is done as it should.

so in a lot of places I got code that is in normal state runs async but in the test I want to wait for the while process to complete before I test's its validity.

So I thought about Promises + returns structure. For example writing the same command twice. first with return that is run only in test and the second doesn't return anything because it's not supposed to wait to that promise to finish. It's the same thing with async/await, I have to write the same command twice. The first with await and the second without.

It looks very dirty though... just the same command that is written twice in the same place...

Here is a code that demonstrates the hackiness of the thing:

if (process.env.NODE_ENV == "test")
    await MailService.sendEmail();
else
    MailService.sendEmail();

So how do you tackle this thing? How to not write the same command twice only for the condition of the await?

Stas Arshanski
  • 423
  • 3
  • 11
  • If your command is only a function calls, this seems fine. If it is more, a) wrap it in a function b) just assign it to a temporary variable. – Bergi Mar 28 '18 at 22:54
  • Don't forget to still [handle errors from promises that you don't want to wait for](https://stackoverflow.com/a/32385430/1048572). – Bergi Mar 28 '18 at 22:55
  • Add the awaits during testing, remove them in the production version. If your file is large, put a comment beside it like `//REMOVEBEFORERELEASE` so you can Ctrl-F (find) it later. – forthe Mar 29 '18 at 01:56
  • Create a generic function that will `await` only in `test env` and wrap your promises with it. – Alex Michailidis Mar 29 '18 at 06:13
  • @alex-rokabilis Tried that. Did not work as expected. – Stas Arshanski Apr 11 '18 at 14:13

0 Answers0