I have an api endpoint which shall return an array of a sum type. How can I write an appropriate matcher for it in pacts (javascript version, consumer site)?
Example: Imagine we have the endpoint /api/events
which returns a list of dictionaries each representing an event. Let's say we have two different types of events (which might be several in practise):
interface ContentAddedEvent {
type: "ContentAdded"
newContent: string
}
interface UserRegisteredEvent {
type: "Userregistered"
username: string
}
type Event = ContentAddedEvent | UserRegisteredEvent
/api/events
returns an array of the type Event[]
. How do I write a matcher for it? I have not found a good example at https://docs.pact.io/implementation_guides/javascript/readme#matching how I can archive it...
Which language are you needing here? It's tagged pact-jvm but it looks to be a JS related question?
In most current implementations, you would need to write a test for each of the two scenarios (i.e. one test for ContentAddedEvent
and another for UserRegisteredEvent
)
See https://docs.pact.io/faq/#why-is-there-no-support-for-specifying-optional-attributes for the challenge of optional types, which is relevant here (TL;DR - if you say you can support both types, but only ever test one variant you can't guarantee the contract is supported, so Pact takes the stance that you must explicitly check all variants in the union).
We have a new matcher that checks for the presence of at least one of each types called arrayContaining
. See https://github.com/pact-foundation/pact-js/tree/feat/v3.0.0#array-contains-matcher for how to use this matcher. It should interoperate between JS and JVM, but the branch is currently in beta
.