I'm trying to write unit tests for Stripe webhooks. The problem is I'm also verifying the stripe-signature
and it fails as expected.
Is there a way to pass a correct signature in tests to the webhook with mock data?
This is the beginning of the webhook route I'm trying to handle
// Retrieve the event by verifying the signature using the raw body and secret.
let event: Stripe.Event;
const signature = headers["stripe-signature"];
try {
event = stripe.webhooks.constructEvent(
raw,
signature,
context.env.stripeWebhookSecret
);
} catch (err) {
throw new ResourceError(RouteErrorCode.STRIPE_WEBHOOK_SIGNATURE_VERIFICATION_FAILD);
}
// Handle event...
And the current test I'm trying to handle, I'm using Jest:
const postData = { MOCK WEBHOOK EVENT DATA }
const result = await request(app.app)
.post("/webhook/stripe")
.set('stripe-signature', 'HOW TO GET THIS SIGNATURE?')
.send(postData);
Stripe now exposes a function in its node library that they recommend for creating signatures for testing:
Testing Webhook signing
You can use
stripe.webhooks.generateTestHeaderString
to mock webhook events that come from Stripe:
const payload = {
id: 'evt_test_webhook',
object: 'event',
};
const payloadString = JSON.stringify(payload, null, 2);
const secret = 'whsec_test_secret';
const header = stripe.webhooks.generateTestHeaderString({
payload: payloadString,
secret,
});
const event = stripe.webhooks.constructEvent(payloadString, header, secret);
// Do something with mocked signed event
expect(event.id).to.equal(payload.id);
ref: https://github.com/stripe/stripe-node#webhook-signing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With