Kinkini Gamage
08/13/2025, 12:38 AMconst stateHandlers = {
"products exists": () => {
controller.repository.products = new Map([
["10", new Product("10", "CREDIT_CARD", "28 Degrees", "5678")],
]);
},
"products exist": () => {
controller.repository.products = new Map([
["10", new Product("10", "CREDIT_CARD", "28 Degrees", "5678")],
]);
},
"a product with ID 10 exists": () => {
controller.repository.products = new Map([
["10", new Product("10", "CREDIT_CARD", "28 Degrees", "5678")],
]);
},
"a product with ID 11 does not exist": () => {
controller.repository.products = new Map();
},
};
My Question:
1. Can I use a real database instead? Instead of manually setting up test data in stateHandlers, can I point my provider verification to use a real database environment (like staging/test DB) to fetch actual data?
2. Can I completely avoid stateHandlers? Is it possible to connect directly to my working environment (staging/test database) and eliminate the need for stateHandlers altogether?
Use Case:
• I want to avoid maintaining test data in code
• Prefer using real data from my test/staging environment
• This would be especially useful for webhook-triggered verifications when consumer contracts are updated
Is this possible/recommended? If so, how would I configure the provider verification to use an actual database connection instead of in-memory test data?
Any guidance or examples would be greatly appreciated! 🙏
Thanks!Matt (pactflow.io / pact-js / pact-go)
404 or other error scenarios. If you find yourself needing to order tests to get them to work, you’re doing it wrong
The point of state handlers is to allow you ability to setup the preconditions required for a test to work. State handlers don’t imply changes to database, it just means “for this test to pass, the following preconditions should be met” - the state handler is responsible for setting up that precondition, however it makes sense.
If you can just pre-load the DB with all the states you need, that’s f ine tooMatt (pactflow.io / pact-js / pact-go)
Is this possible/recommended? If so, how would I configure the provider verification to use an actual database connection instead of in-memory test data?I’m confused about this question - wouldn’t the application naturally use its own database by default? Pact is a unit testing framework, you should try to think about it like that. If you’re pointing at a staging environment, you could do it, but it’s not recommended (what if another test is hitting the environment at the same time - could it mutate the state of the system and interfere with the tests? How will you handle more complicated examples? etc.)