Required, optional, null, empty and extra fields; types and formats
A missing key, an explicit null and an empty value are three states of a field with separate validation branches, so each is its own case. A required field must give an error naming the field, an optional one must succeed. Types, formats, extra fields (a saved role is mass assignment) and a broken structure are checked too; the last must give a controlled 4xx, not a 500.
API · Test design
The email field: missing, null, empty. Is that one case or three?
A developer says: "Email is required, validation exists." You send {}, get 422 and close the case. Meanwhile {"email": null} goes through and the database gets a user with no email, because the check looked only at a missing key. Beyond values, a request body is checked for the presence and shape of each field, and that produces a table of negative inputs.
Below: how "missing", null and "empty" differ, and what to do about types, formats, extra fields and a broken structure.
How it works and why
JSON distinguishes three states of a field, and each goes through its own branch of server code. The deserializer sees a missing key (undefined, or "value not set"), an explicit null and an empty value ("", [], {}). Validation is written as separate conditions, and it is easy to skip one.
Three states of one field
Missing
{ }
"The client did not send the field". In PATCH it means "leave it alone".
null
{ "email": null }
"There is no value". In PATCH it usually means "clear it".
Empty
{ "email": "" }
There is a value, but with no content. A separate case, like a string of spaces.
For a required field we expect a validation error (400 or 422 by agreement) naming the field. For an optional field we expect success and a default value. It also matters whether the server confuses "not sent" with "sent null": in PATCH (JSON Merge Patch, RFC 7396) null means "remove the field" and a missing key means "do not change".
Example: from one negative case to a presence table
Before: one test with {}. It is green, while null and an empty string are unchecked. After: a table where each state is its own test and all of them require the field to be named in the error.
const email = [
{ body: {}, label: 'absent' },
{ body: { email: null }, label: 'null' },
{ body: { email: '' }, label: 'empty string' },
{ body: { email: ' ' }, label: 'spaces only' },
];
for (const c of email) {
test('email ' + c.label, async ({ request }) => {
const res = await request.post('/v1/users', {
data: { name: 'Olena', ...c.body },
});
expect(res.status()).toBe(422);
const body = await res.json();
expect(body.errors[0].field).toBe('email');
});
}
If the "null" row fails with status 201, that is a real defect: validation does not cover an explicit null. Checking errors[0].field guarantees the rejection is about the email and not something else.
Types and formats. For each field take a value of a foreign type. Silent coercion ("30" became 30) is also a defect when the spec says "integer": a client that sends a string breaks once the server changes.
{ "age": "30" } // string instead of an integer
{ "age": 30.0 } // is it an integer? depends on the schema
{ "tags": "a,b" } // string instead of an array
{ "address": [] } // array instead of an object
{ "id": 9007199254740993 } // above 2^53-1: a JS client rounds it
Formats (email, URL, UUID, phone, date and time per ISO 8601, currency and country codes) are checked with three samples: a valid one, one with an error inside, and an edge case (a@b, a trailing space, upper case).
Extra fields. A server may ignore or reject an unknown field, and both behaviours are acceptable if they match the spec. The other variant is dangerous: a field that must not be changeable (role, balance, id) is suddenly stored. That is mass assignment.
test('role in the body is not applied (mass assignment)', async ({ request }) => {
const res = await request.post('/v1/users', {
data: { name: 'Olena', email: 'qa+1@test.example', role: 'admin' },
});
expect([201, 422]).toContain(res.status()); // ignore or reject: per spec
if (res.status() === 201) {
const { id } = await res.json();
const user = await (await request.get('/v1/users/' + id)).json();
expect(user.role).toBe('user'); // must not become admin
}
});
Request structure. Broken JSON, an empty body, a wrong Content-Type, an excessively long body, a duplicate key. Each must produce a controlled 4xx, not a 500.
test('broken JSON gives a controlled 400', async ({ request }) => {
const res = await request.post('/v1/users', {
headers: { 'Content-Type': 'application/json' },
data: Buffer.from('{ "name": "Olena", '), // a Buffer is sent byte for byte
});
expect(res.status()).toBe(400);
expect(res.headers()['content-type']).toContain('json');
});
Limits and alternatives
- "Ignore or reject an extra field" depends on the API. Strict APIs answer 400/422 to an unknown field, lenient ones silently ignore it. The test checks what the spec promises, not personal taste.
- A duplicate key in JSON. RFC 8259 recommends unique names and does not define the behaviour for duplicates: many parsers take the last value, others report an error or all pairs. It is a useful security case (different layers see different values), but the expected response depends on the project.
- Dates. ISO 8601 with a time zone (
2026-11-09T10:00:00Z) and without one may be interpreted differently by the server. Check both. - A schema helps. With OpenAPI, most of the table can be generated from
required,nullable,type,format, but manual cases such as "a string of spaces" still remain with you.
Common mistakes
- Merging the three states into one case. A test with
{}does not prove thatnulland""are rejected too. - Checking only the status of a negative request. A rejection with no state change proves little: after a 422 check that nothing was created, and in an update that the value did not change.
- Accepting type coercion as normal. "It works with a string too" means the contract is blurred, and clients start relying on it.
- Not looking for mass assignment. Add
role,isAdmin,balance,id,ownerIdto create and update and see whether they were stored.
Check yourself
PATCH /users/7 receives { "middleName": null } and { }. How do the expectations differ?
Answer
With null the field is cleared (per JSON Merge Patch), with an empty body nothing changes. A test for it: send null and check that GET returns the field empty (null or absent, per the spec); send another field and check that middleName stayed the same.
The server answered 422 to { "role": "admin", "name": "Olena" } when creating a user. Is that a bug or fine?
Answer
Fine, if the spec says to reject unknown or forbidden fields. It would be a bug if the response were 201 and the role was stored. That is why the test checks not only the status but also that after a 201 role did not become admin.
PATCH they even mean different things. I check extra fields for mass assignment: whether role, balance, id get stored. A broken structure (JSON, Content-Type, a duplicate key) must give a controlled 4xx, not a 500, and I take the table from OpenAPI as a base but add manual cases.