Running promptfoo checks in Mocha and Chai

Learn how promptfoo's assertion functions become custom Chai matchers so prompt quality checks run with the rest of your Mocha suite. Covers setup, mapping, security and failure points.

On this page

Running promptfoo checks in Mocha and Chai: what it does

If your team already runs a Mocha and Chai suite, you can add prompt quality checks to the same run. promptfoo's assertion functions can be wrapped as custom Chai assertions, such as toMatchSemanticSimilarity, so a test reads like any other expectation in your suite. The method is documented in the promptfoo Mocha and Chai guide, which shows how to register the custom assertions and call them from your existing describe and it blocks.

Because the assertions are ordinary Chai expectations, a failing prompt check fails the Mocha run in the same way a broken function would. The checks are not a separate service: promptfoo runs locally on the machine or CI runner executing the tests, and it calls the model under test directly. That means the API keys, model endpoints and any data sent in the test cases sit inside the environment where the suite runs. Confirm with your security team which providers and keys the test runner may reach before you add these checks to a shared pipeline.

Your team should decide which behaviors belong in this suite. Semantic similarity, factuality and LLM grading each rely on a different kind of judgment, and each may call a model that adds cost and latency to every run. Start by listing the prompts you ship, the outputs that must hold, and the expected variation in wording. Then confirm the exact assertion names, options and grading model settings in the current promptfoo documentation for your installed version, since these are the details most likely to change between releases.

Prerequisites for promptfoo in Mocha and Chai

A Mocha and Chai suite that calls promptfoo assertions depends on four things: a Node.js runtime, the promptfoo package, credentials for the model provider the assertions call, and a network path from the CI runner to that provider. Each card below is a check to complete before the first test runs in a pipeline.

Node.js runtime version

The promptfoo release used as the reference here, 0.124.1, requires Node.js 22.22.0 or newer. Confirm the runtime on every CI image and developer machine that runs the suite, because an older Node.js in a shared runner image will fail before any assertion executes. Pin the Node.js version in your pipeline configuration so a runner image update does not change behavior silently.

MIT-licensed npm package

promptfoo is distributed under the MIT license and installed from npm. Your legal or procurement team can review the license terms directly, and the package can be added as a development dependency alongside Mocha and Chai. Record the exact version in your lockfile so the assertion behavior your tests rely on does not change between runs.

promptfoo on npm

Model provider credentials

The semantic similarity, factuality and LLM grading assertions call a model provider, so the suite needs an API key or equivalent credential for that provider. Store the key in your CI secret store, never in the test file or repository, and scope it to the models the grading steps need. Ask who owns the key, how it rotates and what spending limit applies to test runs.

Network access from the runner

Each assertion that uses an LLM makes an outbound call from the CI runner to the provider endpoint. Confirm that the runner can reach that endpoint through your egress rules, proxy and DNS, and that any allowlist includes the provider host your configuration uses. Runners in an isolated network need an approved path or a self-hosted model endpoint inside that network.

Pinned versions and docs check

Confirm the exact promptfoo, Mocha and Chai versions your team pins against the promptfoo Mocha and Chai integration documentation before writing custom assertions. The custom matcher setup and function names come from that page, so a version mismatch between documentation and package is the most likely cause of a broken first run. Record the versions in the pull request that adds the suite.

Mocha and Chai docs

How to wire promptfoo assertions into Chai

This sequence takes a Mocha suite from a plain Chai setup to one that runs promptfoo-backed semantic similarity and LLM grading assertions alongside your existing unit tests. The result is a repeatable test file that fails when a prompt output drifts from what you expect.

  1. Confirm Node.js and project prerequisites

    Check that the machine or CI runner has Node.js 22.22.0 or newer, the version the current promptfoo npm release requires, and that your project already runs Mocha and Chai. Your engineering team owns this check, and you know it is done when node --version reports a supported release and your existing test command runs cleanly before any changes are made.

  2. Install promptfoo as a project dependency

    Add promptfoo to the project with npm so the assertion functions are available to your test files and the version is pinned in the lockfile. Your developers run the install, and you know it is done when promptfoo appears in package.json and the lockfile is committed. Ask your team to confirm the exact release it installs, since the npm registry lists the current version.

  3. Register the custom Chai assertion

    Create a setup file that imports Chai and calls chai.use with the promptfoo-backed plugin that adds assertions such as toMatchSemanticSimilarity to the expect interface. Load this file through Mocha's setup option so every test file gets the assertion. You know it works when a test file can call the new assertion without a reference error.

  4. Call promptfoo assertion functions inside a Mocha test

    Write a Mocha it block that generates output from the prompt under test, then passes that output and the expected reference text to the custom assertion. Keep the model call in the test so the output being graded is the one your application actually produces. Check that the test body reads clearly to a developer who has not seen promptfoo before.

  5. Set the grader provider

    Configure which model acts as the grader for LLM-graded and factuality checks, usually through an environment variable or the provider option that promptfoo reads, and confirm the required API key is supplied from your secrets store rather than committed to the repository. Your security or platform team should review where the key lives. You know this step is done when a grading assertion runs without a missing-provider error.

  6. Add a known-good and a deliberately wrong test

    Write two tests against the same prompt: one with an output that should match the reference, and one with a deliberately incorrect output such as a wrong fact or an unrelated answer. The first should pass and the second should fail. This pair shows that the assertion can discriminate, so a green suite means something. Keep both fixtures in the repository so reviewers can read them.

  7. Run the suite and read the results

    Run the Mocha command your project already uses, with the promptfoo tests included, and check that the known-good test passes, the deliberately wrong test fails with a clear assertion message, and the rest of the suite behaves as before. Your engineers do this run, and you know the wiring is complete when both expected outcomes appear in the output. Confirm with your team which tests should gate merges before adding them to CI.

Which promptfoo assertions map to Chai matchers

The only Chai matcher named in the supplied integration material is toMatchSemanticSimilarity, which compares a model output with an expected value and passes or fails based on how close the meaning is. It needs two inputs: the expected text and the output under test. Factuality and LLM grading are promptfoo assertion types, not names the material confirms as Chai matchers. Before you write them, check the Mocha and Chai integration docs for the exact matcher names your installed promptfoo version exposes. Then write the matcher names and their argument shapes yourselves, so the test code reads the way your team already writes Chai assertions.

For factuality, the natural inputs are a reference answer and the model output, so the matcher needs to know which string is the ground truth. For LLM grading, the inputs are a rubric written in plain language and the output being judged. Decide now whether each matcher takes positional arguments or a single options object, and whether a pass threshold or grader model is passed per call or set once in shared configuration. Confirm which model acts as the grader, where its API key comes from, and whether grader calls count against your provider budget, since each LLM-graded assertion makes an additional model call.

The main risk is a wrapper that hides a failure. If the grader provider is missing or misconfigured, a poorly written wrapper may return an error the Mocha runner reports as an ordinary test failure, or it may pass silently. Before you rely on any matcher, feed it an output you know is wrong and confirm the test fails for the reason you expect. Keep these checks in the same Mocha run as your other tests so a regression in prompt quality blocks the same pipeline stage that blocks a code regression.

Mapping prompt outputs and grading inputs to test assertions

This table maps each element of a Mocha test that checks a prompt, from the output under test to the Mocha test name, showing where each value is defined and who should own it. Read it as a checklist when deciding which fixture or config file holds each input. The main takeaway is that the prompt owner, the test author and the reviewer of grading criteria should not all edit the same value without agreement.

Test elementWhere the value comes fromTypical owner
Prompt output under testReturn value of the function that calls the model, read inside the test bodyApplication engineer who owns the prompt
Reference answerFixture file keyed by test case ID, such as a JSON or YAML file in the test directoryDomain expert who approves expected answers
Grading rubricRubric string stored beside the reference answer, or a shared rubric file for LLM gradingQA or compliance lead who defines acceptance criteria
Grader modelProvider setting in the promptfoo configuration or environment variable for the grading callPlatform team that controls model access and cost
Pass thresholdNumeric threshold argument passed to the custom Chai assertion, kept in a named constantTest author, reviewed when the baseline changes
Mocha test nameString passed to it() that carries the test case ID and the assertion typeTest author, kept stable so reports and history remain comparable
Credentials for graderEnvironment variables loaded from the CI secret store, never written into fixturesSecurity or platform team that manages secrets

Securing API keys, grader models and test data

Mocha and Chai checks call model providers on every run, so they touch provider credentials, a grader model that judges output, and whatever prompts and user data sit in test fixtures. Each of these needs a deliberate decision before the suite runs in a shared pipeline.

Keep provider keys in CI secret stores

Provider keys belong in your CI system's secret store and enter the test process as environment variables at run time. Keep them out of test files, fixture JSON and committed .env files, and make sure test output and failure logs do not echo them. Because promptfoo runs locally and calls the model directly, the key lives on the runner that executes the Mocha suite, so check who can read that runner's logs, cache and workspace.

promptfoo introduction

Pin the grader model explicitly

The matcher that scores semantic similarity or factuality calls a grader model, and that choice changes results. Set the grader in configuration rather than relying on a default, record its exact model identifier, and confirm with the vendor and your own environment which models are approved for your data. A grader change should be a reviewed commit, because it can shift pass and fail outcomes without any change to the application under test.

Scope what reaches the grader

A grader sees the prompt, the output and the reference text it is asked to compare. If those contain customer records, account details or health information, the grader provider receives them too. Decide which provider and region may receive each fixture class, and confirm with your privacy and security teams that the grader route matches the data classification before the suite runs against real content.

Replace production data in fixtures

Test fixtures are copied into repositories, pipeline logs and cached results, so production prompts and user data spread further than intended. Use synthetic or anonymized inputs for assertions, and keep any real examples in a restricted location with a stated purpose. Illustrative rule: a fixture that reproduces a support ticket should replace names and account numbers before it is committed.

Pin promptfoo and Node.js versions

Unpinned dependencies can change matcher behavior between runs without a code change. Pin the promptfoo package version in the lockfile, and confirm the Node.js runtime meets its stated minimum for that release. The current npm release, 0.124.1, requires Node.js 22.22.0 or newer, so a runner image upgrade can break the suite. Upgrade both deliberately and rerun the suite against a known baseline.

promptfoo on npm

Why promptfoo Chai assertions fail in CI

This table lists the failures teams most often hit when promptfoo-backed Chai assertions run in a CI job, with the likely cause and a general fix for each. Scan the cause column first to match a failing build to its source, then apply the fix in your pipeline configuration or test code. Confirm exact runtime requirements against your own environment before you change a working pipeline.

FailureLikely causeFix in general terms
Runtime version errorThe CI image runs Node.js older than the version promptfoo requires, which is 22.22.0 or newer for npm release 0.124.1.Pin the Node.js version in the CI image or setup step to 22.22.0 or newer, and confirm the required version against the current promptfoo release notes before upgrading.
Assertion not foundThe custom Chai assertion was never registered with chai.use, so Chai has no matcher to call.Register the promptfoo assertion plugin once in a shared setup file that loads before any test file runs, following the Mocha and Chai integration docs.
Grader credentials missingThe provider API key is set on a developer laptop but not exposed as a secret to the CI job, or it is scoped to another environment.Store the grader key in the CI secret store, map it into the job environment, and print only the presence of the variable in logs, never its value.
Flaky semantic similarity resultsThe similarity threshold is set too tight for natural variation in model wording, or the same input is judged differently across runs.Set the threshold from a baseline of passing outputs, keep test inputs fixed, and review borderline failures before tightening the bound.
Timeouts on slow LLM callsThe Mocha default timeout is shorter than a round trip to a grader or model, so the test fails before the assertion resolves.Raise the timeout for these suites only, not globally, and reduce the number of model calls per test where the same check can cover more input.
Tests pass without checking anythingThe assertion returns a promise that is not awaited or returned, so Mocha finishes the test before the grader result arrives.Mark the test function async and await or return every promptfoo assertion, then confirm a deliberately wrong expected output fails the build.

Questions teams ask before running promptfoo checks in Mocha

What drives the cost of adding promptfoo checks to a Mocha suite?

The main cost is the engineering time to wire promptfoo assertions into your existing tests, plus the model calls each run makes. Effort rises with the number of suites, the number of Chai assertions that call a model, and how many different grading models you use. Ask any partner for a quote that separates one-time setup (custom assertion helpers, config, CI changes) from recurring costs (model API usage, maintenance as tests change). Because promptfoo runs locally and calls your providers directly, your own provider bills are a cost you will carry whoever builds the integration.

How long does a first promptfoo and Mocha integration usually take?

It depends mainly on how the existing suite is organized and how many assertions you want to convert. A small suite with a few prompt outputs to check is a short, contained piece of work, while a large monorepo with several providers, shared fixtures and strict CI rules takes longer. Expect time for three things: agreeing which outputs need semantic or factuality checks, writing and reviewing the custom Chai assertions, and tuning thresholds against real outputs so tests are stable. Ask for a timeline in the written scope that names the suites in scope and the CI system you will use.

What does our internal team need to provide?

Plan to provide repository access, a place to run the tests (a developer machine or a CI runner), and provider keys for the models that generate outputs and grade them. You also need representative sample outputs from the prompts under test, including good and bad examples, because thresholds for semantic similarity and LLM grading can only be set against real data. Name one engineer who can make decisions about test design and one who owns the CI pipeline. Keep provider keys in your organization's secret store, not in the repository.

Can our engineers build this themselves from the documentation?

Yes, for a team that already runs Mocha and Chai and has someone comfortable with Node.js. The promptfoo documentation for testing prompts with Mocha and Chai describes the custom assertion approach, such as a toMatchSemanticSimilarity assertion backed by promptfoo's assertion functions. The harder parts are not the syntax: they are deciding which outputs deserve a model-graded check, setting thresholds that do not flap, and keeping grading costs under control in CI. Teams without spare capacity, or with several suites to cover, often bring in a partner for the first build and then maintain it internally.

Which parts of the work usually go wrong?

The most common problems are flaky tests caused by nondeterministic model output, thresholds set without real samples, and grader calls that run on every pull request and inflate API spend. Teams also underestimate how much a suite grows once one assertion is accepted. Check that tests are separated by cost (fast deterministic checks on every commit, model-graded checks on a schedule or on prompt changes), that failures produce readable messages, and that someone reviews assertion thresholds when models or prompts change.

When is the free Community edition enough, and when do we need Enterprise?

The Community edition is free and, according to the promptfoo pricing page, includes all LLM evaluation features, all model providers and integrations, and red teaming with 10k probes per month, with community support. For a Mocha integration run by one team inside its own CI, that is usually sufficient. Consider Enterprise only if you need team sharing, teams-based access control and SSO, custom roles and permissions, continuous monitoring, or priority support with SLAs. Enterprise pricing is custom, so request a quote. Self-hosting the promptfoo app for a team has its own limits, which the self-hosting docs describe, including no built-in authentication or SSO in the open-source self-hosted app.

What should we ask for in a written scope before work starts?

Ask for a written scope that lists the Mocha suites and assertions in scope, the model providers and graders used, the CI system and pipeline stages where checks run, the deliverables (custom assertion code, configuration, documentation, handover session), and what is excluded. Also ask how sample outputs and provider keys will be shared and stored, and how threshold changes will be reviewed afterward. A fixed scope with clear acceptance criteria makes it easier to compare quotes from different partners.

How a Mocha test reaches the model and grader

The flow starts in the Mocha runner, which executes a test that calls a custom Chai assertion such as toMatchSemanticSimilarity. That assertion hands the model output to the promptfoo assertion function, which sends the prompt to the model under test and, for LLM grading, to a separate grader model. Scores return through the assertion to Chai, so the test passes or fails with the rest of the suite. Check which side of the trust boundary holds the provider credentials, because those keys are what the CI runner must protect.

Mocha test flow through promptfoo to the model under test and grader.

How DeployOpen scopes and delivers promptfoo test integrations

DeployOpen approaches Mocha and Chai integration as a scoped piece of work inside your existing test suite, not as a separate project. We agree the assertions, test layout, and CI wiring in writing before any code is written, then deliver the integration with documentation your engineers can maintain.

How we scope

  • Inventory which prompt behaviors need Chai assertions, such as semantic similarity, factuality or LLM grading, and which stay as plain unit tests.
  • Confirm the model providers and grader models the suite will call, and where API keys are stored in your environment.
  • Agree in writing the deliverables, the test files covered, the timeline and what your team provides, since engagements are fixed-scope.

How we build

  • Write custom Chai assertions such as toMatchSemanticSimilarity on top of promptfoo's assertion functions, following your existing Mocha conventions.
  • Keep promptfoo-backed tests separate from fast deterministic tests so the wider suite stays quick and predictable.
  • Wire the suite into your current CI system and verify that failing prompt checks block the pipeline as agreed in the scope.

How we hand over

  • Deliver the assertion library, test files, configuration and run instructions in your repository with a short maintenance guide.
  • Document the provider, grader and environment settings each developer needs locally and in CI, without storing secrets in code.
  • Walk your engineers through adding a new prompt check so the team can extend coverage without outside help.

How we support

  • Ongoing support, upgrades and continuous testing are available as a retainer, including updates when promptfoo or Mocha releases change behavior.
  • Review grader drift and flaky LLM-judged results with your team and agree the thresholds that count as a failure.
  • Confirm with DeployOpen during scoping which support level, response expectations and handover materials are included in your quote.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.