How should one match a response value of `null` OR...
# pact-js
é
How should one match a response value of
null
OR
string
with the matchers?
t
1) To match null, just use
null
, no matcher is required 2) To match any string, use
string()
If your response might be either of two types (for example, a null, or a string), then you need two interactions.
This is by design, there’s a docs page on it - one moment
the tl;dr is that if pact let you specify
or
types, then you might incorrectly pass when your provider never actually returns the string
There’s a subtlety here - a matcher is not for saying “here’s a description of every response that the provider can make”, it’s for saying “this test covers everything that would pass this matcher”
💯 1
Complete aside: I kind of think that returning
null
in a payload is an anti-pattern. Null isn’t really a member of
string
, and if you let it be nullable, then you have to write null checks everywhere. Often then you end up with
const someVar = response?.property?.field
, where each thing that could be null has a different meaning, but they’ve all collapsed to one very hard to reason about variable (what does it mean if
someVar
is null?). This makes bugs hard to find, as you can’t easily tell the difference between “missing” and a programmer mistake. And allowing this kind of pattern discourages thinking about the unhappy path. I prefer explicit typing, where you would be able to reason about which fields must be present on each type of object, or you might have a reasonable default for fields that are not present - do you really need to have
null
and
""
? I think this in general leads to better designed APIs. Of course, you didn’t come here to ask if
null
should be in your payload - the above is all my opinion, and you can totally use pact to test payloads that are nullable. However, you’ll have to write a separate test for it, because if pact allowed an OR field, then you couldn’t be sure you’d verified it.
👀 1
é
Thanks for the subtlety and the suggestion about
null
and
""