Skip to content
GuidesChecked 20 November 2026

Test a SwiftUI feedback screen

Swap the network transport and token store to test votes offline and keep SwiftUI previews harmless.

Free for one project and 100 votes. Paid plans start with a 14 day trial, no card.

Two seams

The client takes a transport and a token store as arguments, so a test replaces both and the rest of the package runs as shipped.

Swap the network and the storage, and nothing else.

Name the project in the initializer, or the client makes one extra request to find it.

The client is VoteFirstClient. Its initializer accepts a Transport, which sends each request, and a TokenStore, which keeps the voter token. In a test you pass your own transport and the InMemoryTokenStore the package ships. That store keeps the token in memory, so a test writes nothing to the keychain, inherits nothing from the last run and leaves nothing behind.

Use the form of the initializer that takes a project name and a key. Naming the project skips the request that would otherwise go and find the slug, and that request is one more answer your script would have to supply. The key can be any string that starts with vf_pk_, because no real server is listening.

One piece is not a seam. The offline queue is always a file under the project name. Two tests that share a project name share a queue, so give each test a project name of its own, such as test followed by a fresh UUID.

ClientFactory.swift
import Foundation
import VoteFirst

func makeClient(_ transport: Transport) throws -> VoteFirstClient {
    guard let host = URL(string: "https://example.invalid") else { throw URLError(.badURL) }
    return try VoteFirstClient(
        project: "test-\(UUID().uuidString)",
        key: "vf_pk_test",
        host: host,
        transport: transport,
        tokenStore: InMemoryTokenStore()
    )
}

A scripted transport

A Transport is a single method. A stub that pops the next scripted answer, and remembers every request, covers most tests you will write.

Answer each request from a list you wrote.

Make it an actor, so a test can read the requests from anywhere.

The stub holds a list of statuses and bodies. Each call to send records the request, removes the first entry and returns it as a response. When the list is empty it throws a URLError for no internet connection, which is also how a test goes offline.

An actor beats a class with a lock here. The send method is async, and the test that reads the recorded requests runs somewhere else, so awaiting the stub's requests property is the natural way to assert what left the app.

Every write mints a voter first, so the first scripted answer is nearly always the identity. After it comes the answer to the write itself. Both bodies use the same envelope, with data, meta and error all present. The package decodes one shape, and a stub that leaves a field out will fail for the wrong reason.

StubTransport.swift
actor StubTransport: Transport {
    private var script: [(status: Int, body: String)]
    private(set) var requests: [URLRequest] = []

    init(_ script: [(status: Int, body: String)]) {
        self.script = script
    }

    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
        requests.append(request)
        guard script.isEmpty == false else { throw URLError(.notConnectedToInternet) }
        let step = script.removeFirst()
        guard let url = request.url,
              let response = HTTPURLResponse(url: url, statusCode: step.status,
                                             httpVersion: "HTTP/1.1", headerFields: nil)
        else { throw URLError(.badServerResponse) }
        return (Data(step.body.utf8), response)
    }
}
Bodies.swift
let identity = """
{"data":{"voter_id":"anon_1","kind":"anonymous","anon_token":"tok_1",
"display_name":"BraveOtter_1","banned":false,"voted_feature_ids":[]},"meta":null,"error":null}
"""

let vote = """
{"data":{"feature_id":7,"has_voted":true,"vote_count":4,"score":4},"meta":null,"error":null}
"""

Going offline

An empty script throws a URLError, the package reports a network error, and the write goes into the queue exactly as it would on a train.

Let the script run dry and the app thinks it has no signal.

Expect more than one recorded request, because each call is attempted up to three times.

Start the stub with no entries and call upvote. The first thing to fail is the voter, because minting one is a request too. The write is queued anyway and the voter is minted later, when the queue drains. Your test sees a network error thrown, and a waiting count of one.

Retries matter to the numbers you assert. A failed request is attempted up to three times, with a quarter of a second and then half a second between them.

A stub that throws every time will therefore record several requests for one call, and the test will take a moment. Assert that the count is at least one, or compare it against the three attempts, rather than guessing a single request.

To test the recovery, build a second stub whose script holds the identity and the vote, and call send on the same client. It mints the voter, replays the write in the order it was made and returns how many left the queue. The waiting count then goes back to zero.

OfflineVoteTests.swift
import XCTest
import VoteFirst

final class OfflineVoteTests: XCTestCase {
    func testVoteWithNoNetworkIsQueued() async throws {
        let stub = StubTransport([])
        let client = try makeClient(stub)

        do {
            _ = try await client.upvote(featureID: 7)
            XCTFail("expected a network error")
        } catch let error as VoteFirstError {
            guard case .network = error else { return XCTFail("wrong error") }
        }

        let queued = await client.waiting
        XCTAssertEqual(queued, 1)
        let attempts = await stub.requests.count
        XCTAssertGreaterThanOrEqual(attempts, 1)
    }
}

Refusals

A refusal is a status plus an envelope whose error holds a code and a message. Script one, then assert on the sentence your screen draws.

Answer with an error envelope and check what the user reads.

A refused write must not be queued, so assert a waiting count of zero.

A refusal needs the status to match the envelope. Script the identity, then an answer whose error carries a code such as not_allowed, a message and a field. The package throws a VoteFirstError that carries the typed code, so a test can branch on it the way your screen does.

Test each code your screen words differently. A banned voter, a failed validation and a rate limit each deserve one case, because each should end in a plain sentence rather than a form that silently does nothing. Check the text on screen, not only the thrown error, since the text is what a person sees.

Two outcomes are settled inside the package, and you do not test them in your own code. A vote that is already there and a copy of a write that is still running never reach your screen as failures. What you can assert instead is that a refused write stays out of the queue, since asking again would only be refused again.

A refused vote
let refused = """
{"data":null,"meta":null,"error":{"code":"not_allowed","message":"this column does not accept votes","field":null}}
"""

let stub = StubTransport([(201, identity), (403, refused)])

Your view model

A view model that is given a VoteFirstClient can be tested with a stub. One that reaches for the shared client cannot.

Hand the client to the view model, never reach for it.

The shared client only helps when you start it against a harmless host.

The package keeps one shared client behind the VoteFirst name, and calling start again replaces it. That lets a test point the whole package at a harmless host. It still uses the real transport, so it is no help when the test must run with no network at all.

For a test with no network, build your own client with the stub and pass it in. The view model stores it, calls it, and exposes plain values such as voted, a note and a waiting count. The test drives the model and asserts those values, with no view in sight.

This is also the quickest way to cover the button. Draw it from state your test can set. A disabled button for a closed column, a sentence for a banned voter and a waiting line for a queued vote each become a three line test.

VoteModel.swift
import VoteFirst

@MainActor
final class VoteModel: ObservableObject {
    @Published var voted = false
    @Published var waiting = 0
    @Published var note: String?
    private let client: VoteFirstClient

    init(client: VoteFirstClient) { self.client = client }

    func vote(featureID: Int) async {
        note = nil
        do {
            voted = try await client.upvote(featureID: featureID).hasVoted
        } catch let error as VoteFirstError {
            if case .network = error { voted = true } else { note = error.errorDescription }
        } catch {}
        waiting = await client.waiting
    }
}

Previews

A preview that builds its client from a stub draws in a second, shows any state you script, and sends nothing to a server.

Give every preview a stub, so canvas never calls out.

One preview per state is a quick visual check of each answer.

The same seam serves the canvas. Build the view model from a client that uses the stub transport and an in memory token store, and the preview needs no signal, no key that matters and no board. Script one state per preview, for example a plain vote, an offline vote and a refusal, and you can see all three side by side.

Keep the host on an address that cannot resolve, such as the example.invalid used above. If a preview ever falls through to a real call, it fails fast and quietly instead of leaving a vote on your live board.

VoteButton preview
#Preview("Offline") {
    VoteButton(model: VoteModel(client: previewClient(StubTransport([]))))
}

A real board

A test against production should only read. A test that votes leaves votes, and one that suggests leaves an item in your moderation queue.

Read from the live board, write only to one you can spare.

A second project, or a local stack, is the right place for writes.

Scripted tests prove your code handles the answers you imagined. A small number of tests against a real board prove the answers are the ones you imagined. Point them at a second project made for the purpose, or at a local stack, and call start with that host.

A board behaves the same wherever it runs, including its budgets, its moderation queue and its conflicts. So a local run teaches you real behavior, and it is the only place to try the limits without spending your production project's minute.

The package also ships a sample app in its Examples folder. It shows every view against a host and project you give it, which makes it the fastest way to see a screen before you decide where it goes.

On a device

Run one pass by hand before each release. Open the board once in airplane mode and vote there.

Some things only break on a real phone.

Then turn the network on and watch the vote arrive.

Scripts cannot prove that the queue file survives the app being killed, or that your reachability code calls send at the right moment. A short manual pass can. Vote in airplane mode, kill the app, reopen it, switch the network on and check that the waiting line empties.

Add three more checks to the same pass. A column closed to votes should draw a disabled button, not one that fails. A banned voter should see a sentence, not a form. And the key in the binary should start with vf_pk_ and belong to the right project.

What a testable screen gives you

No network needed

Tests and previews run from a script, on any machine, in any order.

No leftover state

An in memory store and a fresh project name keep each run clean.

Every error covered

Each refusal your screen words can be scripted and checked on its own.

Test a feedback screen in four steps

Each step needs no server and no signal.

Build a client from a stub

Pass a scripted transport, an in memory store and a fresh project name.

Script the answers

List the identity first, then the vote, or leave the list empty for offline.

Assert what the user sees

Check the voted flag, the waiting count and the sentence on screen.

Preview each state

Give every preview its own stub so the canvas never calls out.

What to know before you rely on it

  • This guide covers package 0.3.0, so recheck the calls after a minor release.
  • The offline queue is a file, so give each test its own project name.
  • A scripted test proves your handling, and only a real device proves the queue survives a relaunch.
  • A test that writes to a real board leaves votes and suggestions behind.

iOS vote testing questions

How does the package run with no network in a test?

Pass your own transport and an InMemoryTokenStore to VoteFirstClient. A stub that answers from a list needs no server.

How does a test go offline?

Let the stub throw a URLError. The package reports a network error and queues the write.

Why does my stub record several requests for one vote?

Each call is attempted up to three times, so a stub that keeps failing sees every attempt.

Why give every test its own project name?

The offline queue is a file named for the project, so tests sharing a name would share a queue.

Can your own view be tested with the shared client?

Not without a network. Pass a client into your view model instead, and the stub does the rest.

Is it safe to test against my live board?

Only for reads. A vote or a suggestion from a test stays on the board, so write to a second project.

Which versions does this cover?

Written against package 0.3.0, on iOS 15 or macOS 12 and later.

What does testing cost?

Nothing extra. Free covers one project and 100 votes, and a second project for tests needs Pro at $39/mo, which opens with a 14 day trial and no card. Lite at $9/mo holds one project.

Ship a feedback screen you have tested

Start on Free with one project and 100 votes. When your tests need a second project, Pro is $39/mo after a 14 day trial with no card.