Platform docs
Auth, users, webhooks & more

Testing Your Integration

Automated tests for a Stream Chat integration can run against a real Stream app without touching production. This page shows how to set one up and how to test expired tokens, reconnection and failed sends with the JavaScript client, which runs in Node.js next to your test runner.

Which chat SDKs make it easy to test reconnection, expired tokens and failed sends automatically without relying on our production chat backend?

With Stream Chat, give your tests their own app and drive it from your test runner. The Stream Chat JavaScript client (stream-chat) connects real users from Node.js, so a test can let a token expire, drop the connection and send messages the API refuses, then check what the client does. Each case below is a test you can run with the Node.js test runner.

Use a separate app for tests

Create a second app in the Stream Dashboard for your tests, and give your test runner its API key and secret. A test app has its own users, channels, settings and webhooks, so a test run can't change production data or send push notifications to real users. Configure it like production, with the same channel types and permissions, so your tests get the same errors your users would.

  • Use unique IDs. Add a run ID to every user and channel a test creates, so runs in parallel don't share data.
  • Clean up. Delete what a run creates with hard deletes, or delete the leftovers on a schedule.
  • Mind the rate limits. A test app has rate limits like any other app. Deleting users one call at a time in every test can hit them, so delete in batches.

The tests on this page share one helper that connects a user the way your app does, with a token from your backend:

test/stream.mjs
import { StreamClient } from "@stream-io/node-sdk";
import { StreamChat } from "stream-chat";

// The test app's credentials, never production's
export const apiKey = process.env.STREAM_API_KEY;
export const server = new StreamClient(apiKey, process.env.STREAM_API_SECRET);
export const runId = Date.now().toString(36);

export async function connect(userId, tokenOrProvider) {
  const chat = new StreamChat(apiKey, { allowServerSideConnect: true });
  await chat.connectUser(
    { id: userId },
    tokenOrProvider ?? server.generateUserToken({ user_id: userId }),
  );
  return chat;
}

allowServerSideConnect turns off the warning the client logs when it connects a user from a server, which is what a test does on purpose.

Test expired tokens

To test the refresh path, have your backend issue tokens that expire after a few seconds. Keep them valid for 10 seconds or more: the client waits up to a few seconds before it retries with a new token, and a shorter token can expire again before it is used.

// $expiration is a duration in seconds
$token = $client->createUserToken("ana", expiration: 10);

When a client connects with a token provider, a request made with an expired token fails with error code 40, and the client calls the provider for a new token and sends the request again. When it connects with a token string instead, it can't get a new one, so connecting with an expired token fails:

test/tokens.test.mjs
import { test } from "node:test";
import assert from "node:assert/strict";
import { StreamChat } from "stream-chat";
import { apiKey, connect, runId, server } from "./stream.mjs";

const userId = `test-ana-${runId}`;
await server.upsertUsers([{ id: userId }]);

test("gets a new token when the old one expires", async () => {
  let calls = 0;
  const chat = await connect(userId, async () => {
    calls++;
    return server.generateUserToken({
      user_id: userId,
      validity_in_seconds: 10,
    });
  });
  await new Promise((resolve) => setTimeout(resolve, 12_000));

  await chat.queryChannels({
    filter_conditions: { members: { $in: [userId] } },
  });
  assert.equal(calls, 2);
  await chat.disconnectUser();
});

test("rejects an expired token when there is no provider", async () => {
  const chat = new StreamChat(apiKey, { allowServerSideConnect: true });
  const expired = server.generateUserToken({
    user_id: userId,
    exp: Math.floor(Date.now() / 1000) - 60,
  });

  await assert.rejects(
    chat.connectUser({ id: userId }, expired),
    /token is expired/,
  );
  await chat.disconnectUser();
});

In your app, the token provider calls your backend. See Token Providers and How to Refresh Expired Tokens.

Test reconnection

closeConnection closes the client's WebSocket and keeps the user, and openConnection connects again, as when a phone loses its network and gets it back. On reconnect, the client reloads every active channel and then emits connection.recovered, so the messages sent while it was offline are in the channel's state. A UI SDK marks a channel active while its screen is open. A test without UI calls channel.activate() itself:

test/reconnection.test.mjs
import { test } from "node:test";
import assert from "node:assert/strict";
import { connect, runId, server } from "./stream.mjs";

const [ana, ben] = [`test-ana-${runId}`, `test-ben-${runId}`];
await server.upsertUsers([{ id: ana }, { id: ben }]);
const serverChannel = server.chat.channel("messaging", `test-${runId}`);
await serverChannel.getOrCreate({
  data: { created_by_id: ben, members: [{ user_id: ana }, { user_id: ben }] },
});

test("catches up on messages sent while offline", async () => {
  const chat = await connect(ana);
  const channel = chat.channel("messaging", `test-${runId}`);
  await channel.watch();
  channel.activate();

  await chat.closeConnection();
  await serverChannel.sendMessage({
    message: { text: "Sent while you were offline", user_id: ben },
  });
  const recovered = new Promise((resolve) =>
    chat.on("connection.recovered", resolve),
  );
  await chat.openConnection();
  await recovered;

  assert.ok(
    channel.messagePaginator.items.some(
      (m) => m.text === "Sent while you were offline",
    ),
  );
  await chat.disconnectUser();
});

Test failed sends

A send can fail in two ways, and a test checks each differently.

The API rejects the request. The call throws an error that carries the Stream error code and the HTTP status. These are the codes a send most often gets:

Code Status When
16 404 The channel doesn't exist.
17 403 The user isn't allowed to send there, for example because they aren't a member.
40 401 The token expired and the client has no token provider.
60 403 Slow mode is on and the user sent again too soon.
9 429 The app hit a rate limit.

The API refuses the message. The request succeeds, but the message comes back with the type error and a text that says why, and it isn't stored. This happens to a message longer than the channel type's max_message_length, or one sent to a frozen channel.

test/sends.test.mjs
import { test } from "node:test";
import assert from "node:assert/strict";
import { connect, runId, server } from "./stream.mjs";

const [ana, ben] = [`test-ana-${runId}`, `test-ben-${runId}`];
await server.upsertUsers([{ id: ana }, { id: ben }]);
const serverChannel = server.chat.channel("messaging", `sends-${runId}`);
await serverChannel.getOrCreate({
  data: { created_by_id: ben, members: [{ user_id: ana }, { user_id: ben }] },
});
await server.chat.channel("messaging", `private-${runId}`).getOrCreate({
  data: { created_by_id: ben, members: [{ user_id: ben }] },
});

test("rejected requests throw an error with a code", async () => {
  const chat = await connect(ana);

  await assert.rejects(
    chat
      .channel("messaging", `missing-${runId}`)
      .sendMessage({ message: { text: "Hi" } }),
    { code: 16, status: 404 },
  );
  await assert.rejects(
    chat
      .channel("messaging", `private-${runId}`)
      .sendMessage({ message: { text: "Hi" } }),
    { code: 17, status: 403 },
  );

  await serverChannel.update({ cooldown: 30 });
  const channel = chat.channel("messaging", `sends-${runId}`);
  await channel.sendMessage({ message: { text: "First" } });
  await assert.rejects(channel.sendMessage({ message: { text: "Second" } }), {
    code: 60,
    status: 403,
  });
  await serverChannel.update({ cooldown: 0 });

  await chat.disconnectUser();
});

test("refused messages come back with the type error", async () => {
  const chat = await connect(ana);
  const channel = chat.channel("messaging", `sends-${runId}`);

  const tooLong = await channel.sendMessage({
    message: { text: "x".repeat(5001) },
  });
  assert.equal(tooLong.message.type, "error");

  await serverChannel.updateChannelPartial({ set: { frozen: true } });
  const frozen = await channel.sendMessage({ message: { text: "Hi" } });
  assert.equal(frozen.message.type, "error");

  await chat.disconnectUser();
});

Run all of them with node --test "test/*.test.mjs".

Going further