Updated on November 24, 2026
To test a WhatsApp bot without relying on a phone, split the bot along two boundaries: the input (the webhook payload) and the output (the send call). In your tests, you inject simulated payloads in Meta’s exact format and swap the real sender for a fake one that records what the bot would try to send. Only the last layer, staging, uses the real API, with Meta’s test number or a number separate from production.
This article builds on how to test the webhook locally with ngrok, which covers the connection between Meta and your machine. Here the focus is what comes next: automated tests that run in CI in seconds, with no network and no real customer.
The four testing layers
| Layer | What it tests | Uses Meta? | Runs in CI? |
|---|---|---|---|
| Unit | Payload parser, signature, business rules | No | Yes |
| Flow | Full conversations with simulated payloads and a fake sender | No | Yes |
| Endpoint integration | Real HTTP route: signature, 200, deduplication | No | Yes |
| Staging | Real sending and receiving, on a number that is not production | Yes | Manual or scheduled |
Most bot bugs show up in the first two layers: a field read from the wrong place, a button title that is too long, a duplicated reply. They take milliseconds to run, so it pays to have plenty of them.
Separate input, logic and output
A testable bot receives the payload and a sender object as parameters, instead of calling the API directly:
# bot.py
RANK = {"sent": 1, "delivered": 2, "read": 3}
MENU = [("confirm", "Confirm"), ("reschedule", "Reschedule")]
class MemoryStore:
def __init__(self):
self.seen: set[str] = set()
self.status: dict[str, str] = {}
def first_time(self, wamid: str) -> bool:
if wamid in self.seen:
return False
self.seen.add(wamid)
return True
def apply_status(self, wamid: str, status: str) -> None:
current = self.status.get(wamid)
if status == "failed" or current is None:
self.status[wamid] = status
elif current != "failed" and RANK.get(status, 0) > RANK.get(current, 0):
self.status[wamid] = status
def handle_event(payload: dict, sender, store: MemoryStore) -> None:
for entry in payload.get("entry", []):
for change in entry.get("changes", []):
value = change.get("value", {})
for msg in value.get("messages", []):
if store.first_time(msg["id"]):
handle_message(msg, sender)
for st in value.get("statuses", []):
store.apply_status(st["id"], st["status"])
def handle_message(msg: dict, sender) -> None:
to = msg["from"]
if msg["type"] == "text":
sender.buttons(to, "Can you confirm your appointment tomorrow at 2 p.m.?", MENU)
elif msg["type"] == "interactive" and msg["interactive"]["type"] == "button_reply":
choice = msg["interactive"]["button_reply"]["id"]
if choice == "confirm":
sender.text(to, "Appointment confirmed. See you tomorrow!")
elif choice == "reschedule":
sender.text(to, "No problem. Which day works best for you?")
else:
sender.text(to, "For now I only understand text and buttons.")
In production, sender is the class that makes the POST to /messages. In tests, it is a fake. apply_status already handles a real-world detail: Meta’s status webhook reference explains that if the customer reads the message with the chat open, the delivered webhook may not be sent, and read arrives directly. A status should never “go back” from read to delivered. More on this in message and status ordering in the webhook.
Want to try it while you read? Create a Vectalk account and send your first message through the official API. Create free account →
Fixtures: payloads in Meta’s format
Build payloads with small functions instead of pasting huge JSON blobs into every test. The envelope follows the format documented by Meta and forwarded unchanged by Vectalk, according to Vectalk’s webhook documentation:
# tests/fixtures.py
CUSTOMER = "5511988887777"
def envelope(value: dict) -> dict:
return {
"object": "whatsapp_business_account",
"entry": [{
"id": "WABA_ID",
"changes": [{
"field": "messages",
"value": {
"messaging_product": "whatsapp",
"metadata": {
"display_phone_number": "5511999990000",
"phone_number_id": "PHONE_NUMBER_ID",
},
**value,
},
}],
}],
}
def text_msg(body: str, wamid: str = "wamid.T1", frm: str = CUSTOMER) -> dict:
return envelope({
"contacts": [{"profile": {"name": "Test Customer"}, "wa_id": frm}],
"messages": [{
"from": frm, "id": wamid, "timestamp": "1764000000",
"type": "text", "text": {"body": body},
}],
})
def button_reply(button_id: str, title: str, wamid: str = "wamid.B1", frm: str = CUSTOMER) -> dict:
return envelope({
"contacts": [{"profile": {"name": "Test Customer"}, "wa_id": frm}],
"messages": [{
"from": frm, "id": wamid, "timestamp": "1764000100",
"type": "interactive",
"interactive": {"type": "button_reply", "button_reply": {"id": button_id, "title": title}},
}],
})
def status(wamid: str, value: str, code: int | None = None) -> dict:
st = {"id": wamid, "status": value, "timestamp": "1764000200", "recipient_id": CUSTOMER}
if code is not None:
st["errors"] = [{"code": code, "title": "simulated error"}]
return envelope({"statuses": [st]})
Have at least one fixture for each message type the bot handles (text, button, list, image, location) and for each status (sent, delivered, read, failed). The formats for each type are in webhook payload examples.
If you already store raw events in production, they are the best source of fixtures, because they show cases nobody thought to simulate. Before committing them to the repository, replace phone numbers, names and content with fictitious values. Customer personal data in Brazil is covered by the LGPD (Lei 13.709/2018, Brazil’s general data protection law, similar in spirit to the GDPR); talk to your legal team about what can be kept and for how long. This article is not legal advice.
The fake sender that enforces limits
The fake does more than record calls: it also enforces Meta’s limits, so that an overly long text breaks the test instead of production.
# tests/fake_sender.py
class FakeSender:
def __init__(self):
self.sent: list[dict] = []
def text(self, to: str, body: str) -> None:
assert 0 < len(body) <= 4096, "text over 4,096 characters"
self.sent.append({"to": to, "type": "text", "body": body})
def buttons(self, to: str, body: str, options: list[tuple[str, str]]) -> None:
assert len(body) <= 1024, "button body over 1,024 characters"
assert 1 <= len(options) <= 3, "maximum of 3 buttons"
for button_id, title in options:
assert len(title) <= 20, f"title '{title}' over 20 characters"
assert len(button_id) <= 256, "button id over 256 characters"
self.sent.append({"to": to, "type": "buttons", "body": body, "options": options})
The numbers come from Meta’s pages: up to 4,096 characters for text messages; up to 3 buttons, titles up to 20 characters, ids up to 256 and a body up to 1,024 for reply buttons. The remaining limits are in WhatsApp Business API character limits.
Flow tests
With fixtures and the fake sender, each conversation becomes a readable test:
# tests/test_flow.py
from bot import MemoryStore, handle_event
from tests.fake_sender import FakeSender
from tests.fixtures import CUSTOMER, button_reply, status, text_msg
def test_first_message_shows_buttons():
sender, store = FakeSender(), MemoryStore()
handle_event(text_msg("hi"), sender, store)
assert sender.sent[0]["type"] == "buttons"
assert sender.sent[0]["to"] == CUSTOMER
def test_confirm_replies_with_confirmation():
sender, store = FakeSender(), MemoryStore()
handle_event(text_msg("hi"), sender, store)
handle_event(button_reply("confirm", "Confirm"), sender, store)
assert sender.sent[-1]["body"] == "Appointment confirmed. See you tomorrow!"
def test_duplicate_event_does_not_reply_twice():
sender, store = FakeSender(), MemoryStore()
event = text_msg("hi", wamid="wamid.DUP")
handle_event(event, sender, store)
handle_event(event, sender, store)
assert len(sender.sent) == 1
def test_read_before_delivered_does_not_regress():
sender, store = FakeSender(), MemoryStore()
handle_event(status("wamid.OUT1", "read"), sender, store)
handle_event(status("wamid.OUT1", "delivered"), sender, store)
assert store.status["wamid.OUT1"] == "read"
def test_failure_is_recorded():
sender, store = FakeSender(), MemoryStore()
handle_event(status("wamid.OUT2", "sent"), sender, store)
handle_event(status("wamid.OUT2", "failed", code=131047), sender, store)
assert store.status["wamid.OUT2"] == "failed"
def test_unknown_type_gets_default_reply():
sender, store = FakeSender(), MemoryStore()
event = text_msg("x")
event["entry"][0]["changes"][0]["value"]["messages"][0]["type"] = "sticker"
handle_event(event, sender, store)
assert "text and buttons" in sender.sent[0]["body"]
The duplicate test exists because Meta may resend the same event; a bot without deduplication replies to the customer twice. The full pattern, with Redis or a unique index in the database, is in duplicate webhooks and idempotency.
Cases worth one test each:
- A message of a type the bot does not handle (sticker, reaction, location).
- A single
POSTwith several messages and statuses together in the same payload. - A
failedstatus with code131047(outside the 24-hour window), which should trigger a template instead of free-form text. - A click on a button from an old message, after the conversation has already moved on.
- Text with emoji, accented characters and line breaks.
Endpoint integration test
The flow layer does not go through the HTTP route. An endpoint integration test makes sure the signature, the 200 code and the routing are right. The signature is an HMAC-SHA256 of the body using the app secret, as described on Meta’s webhook endpoint page:
# tests/test_endpoint.py
import hashlib
import hmac
import json
from tests.fixtures import text_msg
SECRET = "test-secret"
def sign(body: bytes) -> str:
return "sha256=" + hmac.new(SECRET.encode(), body, hashlib.sha256).hexdigest()
def test_webhook_accepts_valid_signature(client):
body = json.dumps(text_msg("hi")).encode()
r = client.post(
"/whatsapp/webhook/",
data=body,
content_type="application/json",
headers={"X-Hub-Signature-256": sign(body)},
)
assert r.status_code == 200
def test_webhook_rejects_tampered_body(client):
body = json.dumps(text_msg("hi")).encode()
signature = sign(body)
r = client.post(
"/whatsapp/webhook/",
data=body.replace(b"hi", b"ok"),
content_type="application/json",
headers={"X-Hub-Signature-256": signature},
)
assert r.status_code == 401
The example uses Django’s client with pytest-django; configuring the secret in tests and the view itself are covered in WhatsApp Business API with Django. For NestJS, the signature test and the path to end-to-end tests with Supertest are in WhatsApp Business API with NestJS. In any framework, make sure the test sends the exact bytes that were signed.
Staging: real tests without touching customers
After CI, you still need to see the message arrive on a phone. Three options, from simplest to closest to production:
- Meta’s test number. On the app’s getting-started screen in Meta for Developers, Meta provides a test number, a temporary token and a field to register the numbers that will receive messages, according to the getting started page. The temporary token expires quickly; for recurring tests, use a system user token.
- The webhook “Test” button. Under WhatsApp → Webhooks → Configuration in the app dashboard, the Test link next to the
messagesfield sends a sample payload to your URL, as shown in Meta’s echo bot tutorial. It is useful for checking that the route responds, not for testing flows. - A dedicated staging number. A second number, with the same template and webhook setup as production, but pointing to the staging environment. It is the only way to test real templates, media and limits faithfully. This number is billed like any other.
| Item | Local | Staging | Production |
|---|---|---|---|
| Number | None (fixtures) | Meta test number or dedicated number | Official number |
| Webhook | localhost + ngrok | Staging URL | Production URL |
| Token | Fake | Staging token | Production token |
| Recipients | None | Team phones | Customers |
Never register the staging URL on the production number. Real customer messages would reach the test environment, which could reply to them.
How to do this with Vectalk
Vectalk forwards the same Meta payload to the registered URLs, so the fixtures above work unchanged. Two specific precautions:
- Vectalk’s webhook documentation says you can register several URLs per instance and that all of them receive the same event. So don’t register the staging URL on the production instance: use a separate instance for the staging number, with its own webhook (
POST https://apis.vectalk.com.br/api/webhooks). - Use one token per environment. Instance tokens, created under Settings → API Tokens (Configurações → API Tokens), only work with the instance they were created for, according to the authentication page. This prevents a staging script from sending through the production number by mistake.
The Hub expects a 200 in under 20 seconds. To check what was actually sent during a test, look at the logs in the dashboard or call GET https://apis.vectalk.com.br/api/messages with status and date filters, described in list messages. To get started, create your account. The big picture of the API is in the guide to the official WhatsApp Business API.
Frequently asked questions
Do I need a phone to test the bot?
Not for most tests. Unit, flow and endpoint integration tests run with simulated payloads only. The phone comes in at staging, to see how the message really looks.
Can I test templates without sending them?
You can validate how the payload is built (name, language, number of parameters) with the fake sender. Approval and rendering only show up on a real send, on the test or staging number. One parameter too many or too few produces error 132000.
How do I simulate send API errors?
Make the fake sender raise the same exception the real client would raise for a specific code (for example, 130429 for the throughput limit) and check that the bot re-queues or gives up as expected.
Don’t mock-based tests hide changes made by Meta?
They can. That is why the staging layer exists, and why it is worth refreshing your fixtures from anonymized real events from time to time. Meta publishes changes in the platform changelog; follow it when you upgrade the Graph API version.
Where did the test message fail if the webhook never arrived?
Start with the WhatsApp webhook not working checklist: subscription to the messages field, a URL with valid HTTPS, a 200 response and the verify token.
Official sources consulted on November 24, 2026: Meta: getting started, Meta: create a webhook endpoint, Meta: status webhook, Meta: echo bot and webhook testing, Meta: text messages, Meta: reply buttons, Meta: error codes, pytest-django: fixtures, Vectalk: webhooks, Vectalk: authentication, Vectalk: list messages.
Put your business on the official WhatsApp
Create your account, connect your number to the official API (you can keep the app with coexistence) and start serving customers and sending messages.
