I've started to write unit tests in Node.js (using TypeScript) for the backend, using Mocha+Chai+Sinon libraries
As part of making the function return a correct output for any given input,
It makes sense for example, in login method:
login(userName: string, password: string) : LoginResult I believe its must to verify that the given username and password are strings and not undefined.
The TypeScript engine will alert when the given input is not string, but it will not alert that the given input is undefined which is invalid input for that unit (the tested method).
Therefore, In the start of the code I am using asserts:
assert(userName !== undefined, 'Given "userName" is "undefined");
assert(password !== undefined, 'Given "password" is "undefined");
And I wonder if this is the correct approuch to use asserts in production code for TDD/defensive programming input validations and validate responses from other methods, or it can be improved somehow.
I am using assert-plus library that can disable the asserts on production based on environment variable which is a plus, but I am not sure if I should since the asserts allows to give much more indicative errors and avoiding running code in unexpected conditions.
Thanks!
isValidUsernameorisValidPassword- but others may say asserts are the way to go. This is an opinion based question due to that, and I'm close-voting as suchif (userName !== undefined) throw new Error('Given "userName" is "undefined"'). You just need to have this in your code unless you want to have cryptic exceptions or even worse, invalidated data. Unless you have your assertions covered by tests (and not every of them can be tested because it depends on the input), it's unreasonable to disable them in production. Probably makes sense to have 2 copies of assert-plus, where one improves debugging and can be disabled in production and another is vital and cannot be disabled.isValidPasswordlogic multiple places in your code and you have to change how it behaves.