So suppose I have a function in my code like this:
const getAccountName = account => `${account.name} ${account.lastName}`;
Now, in the function I'm not doing something like ${account?.name ?? ''}
because in this particular case I'm 100% sure that account will always have a name
and lastName
.
Now in the unit test for the getAccountName
, should I still test with an empty object, or without passing any arguments, etc?
CodePudding user response:
If you expect the function to be used outside of your package, generally you should expect someone may call it incorrectly
However, if it does not break something of fail you generally don't have to, as thrown Error
and undefined
in text is easier to find
If you would write in Typescript, you wouldn't need to check that at all, as if you define function as
const getAccountName = (account: {name: string, lastName: string}) => `${account.name} ${account.lastName}`;
you may expect that noone will to call it incorrectly (but out-of-package safety checks may still be required)
CodePudding user response:
because in this particular case I'm 100% sure that account will always have a name and lastName
It's always a judgement call, but I find that in a sufficiently large application, we're only ever "100% sure that X will always have Y... right now". In three years when some project manager decides "an account can now belong to multiple people", and now you have account.accountHolders[0].name
, how will your function respond?
This is also where a typed language (e.g. typescript) is far more useful than unit tests. Ideally you'd have
const getAccountName = (account: { name: string, lastName: string }) => `${account.name} ${account.lastName}`;
And then when account becomes {accountHolders: { name, lastName }}
, the code that does getAccountName(account)
will cause a compilation error.
Either that or an integration test, something along the lines of
function testAccountCreation() {
const account = createAccount('John', 'Doe')
assert.Equal(getAccountName(account, 'John Doe'))
}
so that you both test both the usage of getAccountName, and the assumption that it depends on (an account has a name and lastName).