How should I configure `testMocks` properly so that Apollo generates the mocks for my unit tests?

I’m trying to generate test mocks for my iOS app using Apollo so I can write unit tests, but I’m stuck on the setup.

My apollo-codegen-config.json works fine for generating normal files, but when I add the testMocks section with SPM and targetName, I get this error:

Error: typeMismatch(ApolloCodegenLib.ApolloCodegenConfiguration.TestMockFileOutput, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: “output”, intValue: nil), CodingKeys(stringValue: “testMocks”, intValue: nil)], debugDescription: “Invalid number of keys found, expected one.”, underlyingError: nil))

When I first ran into this, the main issue was the structure of the testMocks section in my apollo-codegen-config.json.

Make sure it’s an object with exactly one key (output), pointing to a valid path for the generated mocks. For example:

{
  "schemaPath": "schema.json",
  "output": "API.swift",
  "testMocks": {
    "output": "Tests/API_TestMocks.swift",
    "targetName": "MyAppTests"
  }
}

I had forgotten to nest targetName inside the same object as output, and that triggered the Invalid number of keys found error.

Once I fixed that, Apollo generated the mocks perfectly.

I ran into a similar problem when trying to generate test mocks using SPM. The trick is that testMocks cannot contain extra keys outside of output and targetName.

Even having an empty object or a trailing comma can break the decoder. My working setup looked like this:

"testMocks": {
  "output": "Tests/Mocks/TestMocks.swift",
  "targetName": "MyAppTests"
}

After ensuring only these two keys exist and the path is correct, the error disappeared. I’d double-check your JSON formatting too, sometimes invisible characters mess up decoding.

I used Apollo for iOS unit tests, and this error usually comes from the JSON expecting exactly one key at a certain level.

In my case, I had "testMocks": { "output": "…" } but I mistakenly added a nested folder key. Removing that extra key fixed it.

So, for Swift + SPM, try this:

"testMocks": {
  "output": "Tests/Generated/TestMocks.swift",
  "targetName": "MyAppTests"
}

Also, make sure the path points to a file, not a directory.

Apollo will generate a single Swift file for the mocks, and it seems the decoder complains if it finds unexpected keys or structures.