Cypress 15 ๐ฒ Fixtures โ Loading Test Data with cy.fixture
A fixture is a file of test data that the test loads by name. cy.fixture("users.json") reads the file from cypress/fixtures/ and passes its parsed content to the next command. The fixture separates the data from the test: the same user list, the same API response, the same image is stored once and referenced by every test that needs it, and a change to the data is a change to one file rather than a change to every test.
This chapter covers the cy.fixture API, the three ways to access the fixture data, and the alias and cy.intercept patterns that connect a fixture to a stubbed network response. The sections that follow walk through loading a fixture, retrieving it with an alias, and the fixture-plus-intercept pattern that makes a test independent of the real API.
Key point: cy.fixture("name.json") reads from cypress/fixtures/ and yields the parsed content; the three access forms are the .then() callback, the .as("alias") plus cy.get("@alias"), and this.alias with a function () test, and cy.intercept(..., { fixture: "name.json" }) serves the fixture as the response.
a. Loading and accessing a fixture
cy.fixture("users.json") reads the file and yields its parsed JSON. The three ways to access the value are the .then() callback, the alias, and the this context.
// The .then() callback
cy.fixture("users.json").then((users) => {
expect(users).to.have.length(3);
});
// The alias
cy.fixture("users.json").as("users");
cy.get("@users").then((users) => {
expect(users).to.have.length(3);
});
// The this context (function, not arrow)
beforeEach(() => {
cy.fixture("users.json").as("users");
});
it("uses this", function () {
expect(this.users).to.have.length(3);
});
The .then() form is the direct access. The alias form is for a fixture that several commands in the test need, because cy.get("@users") retrieves it without re-reading the file. The this form is the shortest, but it requires the test function to be a function () rather than an arrow function, because the alias is bound to the test context’s this.
The file extension is optional. cy.fixture("users") resolves to users.json by default, and the cy.fixture("users.json") form is explicit. The path is relative to cypress/fixtures/, and a subdirectory is part of the name: cy.fixture("api/users.json") reads cypress/fixtures/api/users.json.
The fixture can be a JSON file, a text file, or an image. The cy.fixture("message.txt") yields the text, and the cy.fixture("logo.png") yields the base64-encoded image, which is the pattern for a file upload test.
b. The fixture and the intercept
The cy.intercept handler accepts a { fixture: "name.json" } object, which serves the fixture as the response. The pattern is the deterministic API stub: the test does not depend on the real backend, and the response is the file the test controls.
cy.intercept("GET", "/api/users", { fixture: "users.json" }).as("getUsers");
cy.visit("/users");
cy.wait("@getUsers");
cy.get("li").should("have.length", 3);
The fixture is read at the time the intercept matches, and the response is the parsed JSON with the 200 status by default. The { fixture, statusCode } form sets a different status, and the { fixture, headers } form sets the headers.
cy.intercept("GET", "/api/users", {
fixture: "users.json",
statusCode: 500,
});
The fixture path is resolved relative to cypress/fixtures/, the same as the cy.fixture call. The { fixture: "api/users.json" } reads the subdirectory, and the { fixture: "users.json" } reads the root.
The fixture can also be used inside the cy.intercept handler function. The req.reply({ fixture: "users.json" }) form is the same as the static object, and the cy.fixture("users.json").then((users) => req.reply(users)) form is the dynamic version for a response that modifies the fixture.
cy.intercept("GET", "/api/users", (req) => {
cy.fixture("users.json").then((users) => {
req.reply(users.slice(0, 2)); // only the first two
});
});
c. The fixture directory and the type
The fixture directory is cypress/fixtures/ by default. The fixturesFolder config option changes the location, and a project that keeps its fixtures in a shared directory points at it.
// cypress.config.ts
export default defineConfig({
e2e: {
fixturesFolder: "cypress/test-data",
},
});
The fixture type is inferred from the file extension. A .json file is parsed as JSON, a .txt file is returned as a string, and a .png file is returned as a base64 string. The cy.fixture("data.csv") returns the raw text, and the test parses it with a CSV library if it needs a structured value.
The TypeScript type of a fixture is not inferred from the file. The cy.fixture("users.json") yields any, and the test casts it or defines the type.
type User = { id: string; name: string };
cy.fixture<User[]>("users.json").then((users) => {
// users is User[]
});
The cy.fixture<T> generic is the type assertion, and it is the pattern for a typed test. The alternative is the as cast, which is the same assertion with a different syntax.
The fixture is a file, and a file can drift from the type it represents. A test that expects a User[] and reads a file that no longer matches the type is a test that fails at the assertion, not at the fixture load. The type is a contract, and the fixture is the data; the two are not checked against each other at runtime.
Complete Example Session
// ============================================
// PART 1: THE FIXTURE FILE
// ============================================
// cypress/fixtures/users.json
// [
// { "id": "1", "name": "Ana" },
// { "id": "2", "name": "Ben" },
// { "id": "3", "name": "Cleo" }
// ]
// ============================================
// PART 2: THE DIRECT ACCESS
// ============================================
describe("direct", () => {
it("reads the fixture", () => {
cy.fixture("users.json").then((users) => {
expect(users).to.have.length(3);
});
});
});
// ============================================
// PART 3: THE ALIAS
// ============================================
describe("alias", () => {
beforeEach(() => {
cy.fixture("users.json").as("users");
});
it("uses cy.get", () => {
cy.get("@users").then((users) => {
expect(users[0].name).to.eq("Ana");
});
});
it("uses this", function () {
expect(this.users).to.have.length(3);
});
});
// ============================================
// PART 4: THE INTERCEPT
// ============================================
describe("intercept", () => {
it("stubs the API with the fixture", () => {
cy.intercept("GET", "/api/users", { fixture: "users.json" }).as("getUsers");
cy.visit("/users");
cy.wait("@getUsers");
cy.get("li").should("have.length", 3);
});
});
// ============================================
// PART 5: THE DYNAMIC REPLY
// ============================================
describe("dynamic", () => {
it("replies with a subset", () => {
cy.intercept("GET", "/api/users", (req) => {
cy.fixture("users.json").then((users) => {
req.reply(users.slice(0, 2));
});
});
cy.visit("/users");
cy.get("li").should("have.length", 2);
});
});
The parts covered the fixture file, the direct access, the alias in both forms, the intercept stub, and the dynamic reply.
Quick Reference
Access Forms
| Form | Code |
|---|---|
| Direct | cy.fixture("f.json").then((d) => ...) |
| Alias | cy.fixture("f.json").as("d") + cy.get("@d") |
this | this.d with function () |
File Types
| Extension | Value |
|---|---|
.json | Parsed object |
.txt | String |
.png | Base64 string |
.csv | Raw text |
Intercept
| Form | Effect |
|---|---|
{ fixture: "f.json" } | Serve the fixture |
{ fixture, statusCode } | Custom status |
req.reply(fixtureData) | Dynamic reply |
Best Practices
โ Do This:
// Use the alias for a fixture used several times
cy.fixture("users.json").as("users"); // โ
// Use the function form for this
it("...", function () { expect(this.users).to.have.length(3); }); // โ
// Type the fixture
cy.fixture<User[]>("users.json").then((users) => { ... }); // โ
โ Don’t Do This:
// Use an arrow function with this
it("...", () => { this.users; }); // undefined // โ
// Re-read the fixture in every command
cy.fixture("users.json").then(() => { ... });
cy.fixture("users.json").then(() => { ... }); // redundant // โ
// Assume the fixture type matches the test type
cy.fixture("users.json").then((users) => users.foo); // untyped // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
this.users undefined | Arrow function | Use function () |
| Fixture not found | Wrong path | Relative to cypress/fixtures/ |
| Fixture type mismatch | No generic | cy.fixture<T> |
| Intercept stub not served | Intercept after the visit | Register before cy.visit |
Real-World Examples
1. Direct access
cy.fixture("users.json").then((users) => { ... });
2. Alias
cy.fixture("users.json").as("users");
3. this access
it("...", function () { expect(this.users).to.have.length(3); });
4. Text fixture
cy.fixture("message.txt").should("contain", "Hello");
5. Image fixture
cy.fixture("logo.png").then((logo) => { ... });
6. Subdirectory
cy.fixture("api/users.json");
7. Intercept stub
cy.intercept("GET", "/api/users", { fixture: "users.json" });
8. Custom status
cy.intercept("GET", "/api/users", { fixture: "users.json", statusCode: 500 });
9. Dynamic reply
cy.intercept("GET", "/api/users", (req) => {
cy.fixture("users.json").then((u) => req.reply(u.slice(0, 2)));
});
10. Typed fixture
cy.fixture<User[]>("users.json").then((users) => { ... });
Visual
The Three Access Forms
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ DIRECT โ
โ cy.fixture("f.json").then((d) => { ... }) โ
โ โ
โ ALIAS โ
โ cy.fixture("f.json").as("d") โ
โ cy.get("@d").then((d) => { ... }) โ
โ โ
โ this โ
โ beforeEach(() => cy.fixture("f.json").as("d")) โ
โ it("...", function () { this.d }) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Fixture Path
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ cypress/fixtures/ โ
โ users.json โโโ cy.fixture("users.json") โ
โ api/ โ
โ users.json โโโ cy.fixture("api/users.json") โ
โ logo.png โโโ cy.fixture("logo.png") โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Intercept Stub
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ cy.intercept("GET", "/api/users", { โ
โ fixture: "users.json", โ
โ }).as("getUsers"); โ
โ โ โ
โ โผ โ
โ The request is answered by the fixture. โ
โ The real server never sees it. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Dynamic Reply
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ cy.intercept("GET", "/api/users", (req) => { โ
โ cy.fixture("users.json").then((users) => { โ
โ req.reply(users.slice(0, 2)); โ
โ }); โ
โ }); โ
โ โ
โ The response is the fixture, modified before it is sent.โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Load | cy.fixture("name.json") |
| Directory | cypress/fixtures/ |
| Direct access | .then((data) => ...) |
| Alias | .as("name") + cy.get("@name") |
this | this.name with function () |
| Intercept | { fixture: "name.json" } |
| Type | cy.fixture<T> |
Key takeaways:
- A fixture is a file of test data loaded by name.
cy.fixture("users.json")reads fromcypress/fixtures/and yields the parsed content, and the same file is referenced by every test that needs the data. - The three access forms are the
.then()callback, the alias, and thethiscontext. The alias is for a fixture several commands need, and thethisform requires afunction ()test. - The
cy.intercepthandler can serve a fixture.{ fixture: "users.json" }is the deterministic API stub, and the dynamicreq.replyform is the version that modifies the fixture before sending it. - The fixture type is not inferred. The
cy.fixture<T>generic is the type assertion, and the test is responsible for the type matching the file. - The fixture path is relative to
cypress/fixtures/. A subdirectory is part of the name, and thefixturesFolderconfig option changes the root.
Remember: A fixture is the data the test does not want to hard-code. Load it with cy.fixture, access it with .then() or an alias, and serve it with cy.intercept when the test needs a deterministic API. The three access forms are the same value with different ergonomics, and the function () test is the requirement for the shortest one.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!