DEV Community

Cover image for The simulator has no camera: how I UI-test a KYC flow
Vadim Toptunov
Vadim Toptunov

Posted on AI-assisted

The simulator has no camera: how I UI-test a KYC flow

Identity verification is a flow most fintech apps have, and one that's awkward to test. You pick a document, point the camera at it, take a selfie, wait, and get a verdict. On a simulator, the first step already fails: there's no camera.

So KYC often ends up tested by hand, on a real phone, with someone's real passport, or not past "the SDK screen opens".

I wanted to see how much of it can be tested automatically, so I added a mock KYC flow to ChaosBank, my practice banking app with switchable bugs (intro post). It has the same steps a real one has, four bugs in the places where real KYC goes wrong, and seven UI tests that catch them.

What the flow looks like

Card → Verify identity. You choose a passport or an ID card, scan it, take a selfie and submit. The result is one of three: Identity verified, Verification failed with a reason, or Under review. A verified identity also unlocks transfers over €1,000, which the app blocks for unverified users.

Behind the screens there are two kinds of code, and the difference matters for testing:

  • Capture: reading the document and checking the face. In a real app this is a vendor SDK talking to the camera.
  • Decision: what the app does with what was captured. Is the document expired? Is it in the account holder's name? Does the face match? What does the user see, and what does the app unlock?

The capture part is hard to test on a simulator. The decision part is plain code that you wrote, and it's where most of the interesting bugs live.

Putting the camera behind a seam

The trick is to keep capture behind a small interface, so a test build can swap in something that doesn't need a camera:

protocol KycDocumentScanning { func scan(_ kind: KycDocumentKind) async -> KycDocumentScan }
protocol KycSelfieChecking { func check(against document: KycDocumentScan) async -> KycSelfieScan }
Enter fullscreen mode Exit fullscreen mode

In ChaosBank the default implementations don't scan anything. They return whatever a launch argument asks for, after a short pause so the UI goes through its loading state:

/// Replays `-ChaosBankKycDocument`: valid | expired | unreadable | nameMismatch.
struct ScriptedDocumentScanner: KycDocumentScanning {
    let script: String
    var now: () -> Date = { Date() }

    func scan(_ kind: KycDocumentKind) async -> KycDocumentScan {
        try? await Task.sleep(for: .milliseconds(600))
        let number = kind == .passport ? "P4916204" : "ID7731205"
        switch script {
        case "expired":
            return KycDocumentScan(name: KycReview.accountHolder, number: number, expiry: KycReview.date(2024, 1, 31))
        case "unreadable":
            return KycDocumentScan(name: nil, number: nil, expiry: nil)
        case "nameMismatch":
            return KycDocumentScan(name: "ALEX MORGAN", number: number, expiry: KycReview.validExpiry(from: now()))
        default:
            return KycDocumentScan(name: KycReview.accountHolder, number: number, expiry: KycReview.validExpiry(from: now()))
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

So a test says what the "camera" sees when it launches the app:

-ChaosBankKycUnverified 1        # start unverified
-ChaosBankKycDocument expired    # valid (default) | expired | unreadable | nameMismatch
-ChaosBankKycSelfie mismatch     # match (default) | mismatch | noFace
Enter fullscreen mode Exit fullscreen mode

On Android the same switches are intent extras (-e CHAOSBANK_KYC_DOCUMENT expired), and the flow, ids and texts are the same.

In a real app you'd put the vendor's SDK behind the same two protocols, and the test build would get the scripted versions. The launch arguments work for anything that can launch the app: XCUITest, Appium, Maestro, or xcrun simctl launch when you just want to look at a screen.

The rules, and the bugs in them

The decision is one function. Each check is written correctly, and each has one guarded point where a ChaosBank defect can switch it off:

static func decide(document: KycDocumentScan, selfie: KycSelfieScan, today: Date = Date()) -> KycOutcome {
    // `kycAcceptsExpiredDocument`: the expiry date isn't checked.
    if let expiry = document.expiry, expiry < today, !Defects.isActive(.kycAcceptsExpiredDocument) {
        return .rejected("Document expired")
    }
    // `kycNameMismatchAccepted`: the document's name isn't compared with the account holder.
    if document.name != accountHolder, !Defects.isActive(.kycNameMismatchAccepted) {
        return .rejected("Name doesn't match the account holder")
    }
    // `kycSelfieMismatchAccepted`: a face that doesn't match still passes.
    if selfie == .mismatch, !Defects.isActive(.kycSelfieMismatchAccepted) {
        return .rejected("Face doesn't match the document")
    }
    // `kycStuckPending`: an approved check is reported as still under review.
    return Defects.isActive(.kycStuckPending) ? .pending : .verified
}
Enter fullscreen mode Exit fullscreen mode

The four bugs are the kind I'd expect in a real KYC integration:

Defect What goes wrong
kycAcceptsExpiredDocument an expired passport passes
kycNameMismatchAccepted a document in someone else's name passes
kycSelfieMismatchAccepted a face that doesn't match the document passes
kycStuckPending an approved check stays "Under review" forever

The first three are security bugs: the check says yes when it should say no. The last one is the opposite. Nothing is unsafe, the user is just stuck, and a test that only checks "the flow finished without an error" won't notice.

There's also a fifth, older defect on the transfer side, kycBypassAllowsTransfer, which lets an unverified user send more than €1,000 anyway.

The tests

The tests are in the ChaosBank × KassiOS reference suite, written on KassiOS, my layer over XCUITest. Each one launches the app with a script and goes through the flow like a user would:

private func openKyc(document: String = "valid", selfie: String = "match") {
    launchUnlocked(tab: "card", extra: [
        "-ChaosBankKycUnverified", "1",
        "-ChaosBankKycDocument", document,
        "-ChaosBankKycSelfie", selfie,
    ])
    onScreen(CardScreen.self) { $0.kycButton.tap() }
}

/// An expired document is rejected. Catches `kycAcceptsExpiredDocument`.
func test_kyc_expiredDocument_isRejected() {
    openKyc(document: "expired")
    onScreen(KycScreen.self) { kyc in
        runFlow(kyc)   // scan → selfie → submit → wait for the result
        kyc.resultTitle.assertLabel("Verification failed")
        kyc.resultReason.assertLabel("Document expired")
    }
}
Enter fullscreen mode Exit fullscreen mode

The other rejection tests look the same with a different script and a different reason. They check the reason as well as the verdict. A test that only checks "Verification failed" would stay green if the app rejected an expired passport for the wrong reason, or rejected everything.

kycStuckPending needed more than that. The happy-path test checks the result screen says Identity verified and that the Card tab says so too. A second test goes one step further and checks what verification is for: after verifying, a €2,000 transfer can continue.

/// After verifying, the same €2,000 transfer can continue.
/// Catches `kycStuckPending` end to end (the gate never opens).
func test_transfer_overKycThreshold_opensAfterVerifying() {
    openKyc()
    onScreen(KycScreen.self) { kyc in
        runFlow(kyc)
        kyc.doneButton.tap()
    }
    onScreen(TabBar.self) { $0.home.tap() }
    onScreen(HomeScreen.self) { $0.transferAction.tap() }
    onScreen(TransferScreen.self) { transfer in
        transfer.recipientField.typeText("Alex")
        transfer.amountField.typeText("2000")
        transfer.continueButton.assertEnabled()
    }
}
Enter fullscreen mode Exit fullscreen mode

Its mirror image checks that the same transfer is blocked while the user is unverified, which catches kycBypassAllowsTransfer. And one test covers the unreadable scan: the error shows up, there's no selfie step, and Submit stays disabled.

That's seven UI tests. On the clean build all of them pass, and each of the five defects turns its own test red when it's switched on alone. kycStuckPending turns two red.

Where unit tests are enough

Not everything here needs a UI test. The rules are a pure function, so the unit tests call decide directly, once with each defect off and once with it on. They also cover things that are awkward to reach through the UI, like tapping "Take selfie" or "Submit" before there's a document, which must do nothing:

func testNothingHappensOutOfOrder() async {
    let model = KycFlowModel(scanner: ScriptedDocumentScanner(script: "valid"), faceCheck: ScriptedSelfieChecker(script: "match"))
    await model.takeSelfie()
    XCTAssertNil(model.selfie, "no selfie before a document")
    let store = KycStore(verified: false)
    await model.submit(to: store)
    XCTAssertNil(model.outcome, "no submit before a document and a face")
    XCTAssertFalse(store.verified)
}
Enter fullscreen mode Exit fullscreen mode

My split: unit tests for the rules and the state machine, UI tests for what the user sees and what verification unlocks. The UI tests are where a missing reason, a wrong label or a transfer that stays blocked shows up.

What this doesn't test

The vendor's SDK. With the camera behind a seam, none of these tests touch the real scanner, the real liveness check or the SDK's own screens. Those still need a real device and a real document, and probably the vendor's own test mode if they have one. What the seam gives you is everything after the SDK hands back its result: the rules, the messages and what the app unlocks. That's the part you wrote, and the part the vendor can't test for you.

While writing this I also found a time bomb in my own fixtures. The scripted "valid" document used to expire on 30 April 2031, and decide compares the expiry with the real date. From 1 May 2031 the happy path would have failed on a correct build with "Document expired", and every test expecting a verified identity would have gone red with no bug switched on. Now a valid document expires five years after the day it's scanned, and the scanner takes a clock, so a unit test can scan a passport "in 2040" and check it still passes. The expired fixture can stay a fixed date: it only has to be in the past.

If your test data has dates in it, it's worth a quick look for the same thing.

Try it

Both ChaosBank apps have the flow. Every KYC defect is in exercises.json with the launch arguments, the locators and what the broken build does, so you can write the tests in whatever framework you use and check them against the defects. To look at a broken build by hand:

xcrun simctl launch booted VadimToptunov.ChaosBank \
  -ChaosBankStartUnlocked 1 -ChaosBankTab card \
  -ChaosBankKycUnverified 1 -ChaosBankKycDocument expired \
  -ChaosBankDefects kycAcceptsExpiredDocument
Enter fullscreen mode Exit fullscreen mode

Go through Card → Verify identity, and an expired passport gets you a verified identity.

If you test KYC at work, I'd like to know how you handle the SDK part: a vendor test mode, a seam like this one, or a real phone and a real passport.

Links

Top comments (2)

Collapse
 
userxnom profile image
Abdullah Naseer •

The seam is the part I'll steal — putting the camera behind a small interface so a test build can script what it sees is a much cleaner answer than fighting the simulator. On Android, the intent-extras version of the same trick is exactly how I'd do it. The honest bit at the end landed too: the vendor SDK is the part nobody tests, and pretending otherwise is worse than admitting it. I haven't written instrumentation tests for my own app yet, so the split you draw — unit tests for the decision, UI tests for what the user sees — is a useful map for where to start.

Collapse
 
vadimtoptunov profile image
Vadim Toptunov •

Thanks! If you start on instrumentation tests, I'd begin with one screen where a wrong decision is easy to see, and get that test to fail on purpose once before trusting it going green.