Saving is off. The course database is down: labs work for practice, but nothing is saved.The course database is down.

LAB07

Hardware, Testing and Deployment — Camera, Haptics, Jest, Maestro and EAS

Build a Smart QR Scanner with the phone’s hardware: the camera permission, reading QR codes with expo-camera, the front and back camera, and vibration feedback with expo-haptics. Then test it on three levels — Jest unit tests, React Native Testing Library component tests and a Maestro end-to-end flow — and turn it into an installable app with EAS Build, then learn EAS Submit and EAS Update. Everything runs in the browser, nothing to install: the code, the phone, the tests (Run tests) and the Maestro flows (Run flow). Real screenshots and terminal output from a phone and a computer, and 21 checked exercises.

Intermediate 3 h 30 minexpo-camerapermissionsqr-codesexpo-hapticsjestreact-native-testing-librarymaestroeas-buildeas-submiteas-update

Your progress

0 / 21 exercises

10 parts · 3 h 30 min

Before you start

Who’s doing Lab 07?

This lab is open any time. Enter your name and student ID to start. Your work is saved.

By the end you will

  • Ask for the camera permission and handle every answer — not known yet, allowed, refused, refused for good (Open settings)
  • Show the camera with CameraView, read QR codes with onBarcodeScanned, and handle one code once with a useRef lock
  • Switch between the front and the back camera, and show camera errors
  • Give vibration feedback with expo-haptics, and explain why Smart QR vibrates after the camera closes
  • Explain unit, component and end-to-end tests, and choose the right one for a bug
  • Write and run Jest unit tests and React Native Testing Library component tests, with fake packages (jest.mock)
  • Read a failing test — the test name, the Expected / Received difference and the code frame
  • Write a Maestro flow and run it on a phone
  • Give the app its id and configure EAS Build profiles in eas.json, and explain APK and AAB and app signing
  • Explain EAS Submit and EAS Update, and choose between an update and a new build

You need

  • Labs 01–06: components, props, useState, useEffect, async / await
  • A computer with a browser (Chrome or Edge). Nothing to install: the editor, the phone, the tests and the Maestro flows all run on this page

Part 1: Meet the Smart QR Scanner

10 min

In this lab you build one app from start to finish: the Smart QR Scanner. It uses the phone’s camera to read a QR code, shows what is inside it (a website, a Wi-Fi network, an email, a phone number or text) and makes the phone vibrate. Then you test it and build it into an app file that anyone can install.

Every part of the lab works the same way: first you understand — real pictures, an animation, the code line by line — then you do it in an exercise.

① What you will build

The finished app, on a real Android phone (an emulator, in Expo Go):

Smart QR home screen on Android: a QR logo, the title Smart QR, the text Scan a QR code and feel the result, and a Start scanning button

1 · Home

The scanner screen: the live camera shows a room, a blue scan frame with a moving line, and the buttons Back, Flip camera and Use sample QR

2 · The camera

The result card: a green check, the label WEBSITE, the text https://expo.dev, an Open link link and a Scan again button

3 · The result

Home → camera → result. When the result card opens, the phone vibrates: a success pattern for a good code, an error pattern for a bad one.

The same app on the lab phone — the phone on this page, which you use in every exercise. One full scan:

● recorded on this page
One scan, from start to finish
  1. The home screen. The finger presses Start scanning.
  2. The app asks for the camera: Allow camera, then the phone’s own dialog, While using the app.
  3. The camera opens. The lab phone has no real camera: the QR codes are buttons. The finger presses QR: Website.
  4. The result card: a green check, WEBSITE and https://expo.dev. The phone vibrates — on the lab phone it shakes, and the Console says Haptics: notification success.

Try it yourself: tap a sample code to “hold it in front of the camera”, and read the Console to see each vibration.

● LIVE DEMOThe finished Smart QR ScannerLoading the editor and preview…

② How it works

Words used in every part:

  • Hardware — the physical parts of the phone: the camera, the vibration motor, the screen.
  • Permission — the user’s answer (yes or no) to “may this app use the camera?”. Phones ask once per app.
  • Haptics — short vibrations that tell the user something happened, like a tap on the finger.
  • Test — code that runs a part of your app and checks the result. It says PASS or FAIL.
  • Build — turning your project into an app file a phone can install (an APK on Android).
  • Native code — the Kotlin (Android) or Swift (iPhone) code inside the phone app. Your code is JavaScript; packages like expo-camera bring the native code that talks to the camera.

The lab follows the life of the app in three stages, and each stage has its own tools. Press Play, or Next for one stage at a time:

The eight tools of this lab

1HardwareParts 3–4
  • expo-cameraShows the live camera and reads QR codes
  • expo-hapticsMakes the phone vibrate
2TestingParts 5–7
  • JestRuns the tests and says PASS or FAIL
  • React Native Testing LibraryDraws one screen in a test and presses its buttons
  • MaestroDrives the real app on a phone, step by step
3DeploymentParts 8–9
  • EAS BuildTurns the project into an app file (APK, AAB, iPhone)
  • EAS SubmitUploads a finished build to Google Play or the App Store
  • EAS UpdateSends new JavaScript to apps already installed
expo-barcode-scannerremoved — QR codes are read by expo-camera now
  1. 1 / 5One app, three stages

    The lab follows the life of one app, Smart QR: first you build it with the phone’s hardware, then you test it, then you ship it to phones. Each stage has its own tools.

③ The project, file by file

The files with a ★ are the ones you write in this lab:

smart-qr-scanner
  • App.tsxtwo screens: Home and Scanner
  • app.jsonthe app’s name, id, icon and the camera plugin
  • package.jsonpackages and the test command
  • src/
  • screens/
  • HomeScreen.tsxthe first screen
  • ScannerScreen.tsxcamera + permission + scan ★ Part 4
  • scan/
  • parseScan.tswhat is inside a QR code
  • feedback.tsthe vibrations ★ Part 4
  • components/
  • AppButton.tsxone button style for the whole app
  • ScanFrame.tsxthe blue frame with the moving line
  • ResultCard.tsxthe result, with its vibration
  • __tests__/unit and component tests ★ Part 6
  • test-utils/fakeCamera.tsxa fake camera for the tests
  • .maestro/scan-sample.yamlthe end-to-end test ★ Part 7
  • eas.jsonbuild profiles ★ Part 9

④ Your turn · Exercise 1

Match each tool to its job. All eight are in the animation above — and one chip is the old package you must leave out.

EX 01Which tool does which job?Loading the exercise…

Checkpoint

You know what Smart QR does, and which tool each part of the lab uses: two packages for the hardware, three tools for testing, three EAS services for deployment.

Part 2: The project in your browser

13 min

There is nothing to install in this lab. The whole Smart QR project runs on this page: each exercise shows the project’s files in an editor, and the lab phone next to it runs them. Your code is the same code a real Expo project runs on a phone; only the phone is a stand-in.

① What you will use: the exercise screen

Every exercise of the lab looks like this. Learn its parts once — the numbers match the list under the picture:

  1. The task: what to do, and how to try it on the phone.
  2. The checklist: what Check tests. Each line turns green when that part works.
  3. The files of the project. Click a tab to open a file.
  4. The editor: write your code here. The TODO comments show where.
  5. The lab phone: it runs the code you write, while you type.
  6. The Console: what console.log prints, the vibrations, and the camera’s answers.
  7. Check: tests your work and says what is still missing.
  8. Reset: back to the starting code of the exercise.
  9. Hint: one hint at a time, when you are stuck.
  10. Open in Code Editor: the same files in BUENOVA’s full editor.

The lab phone is a stand-in for a real phone. Three things are different:

the same as a phone

Your code

The same files, imports and packages (expo-camera, expo-haptics). What passes here runs unchanged in Expo Go.

a stand-in

The camera

A browser has no phone camera, so the camera shows sample QR codes: tap one to hold it in front of the camera. The permission dialog has the phone’s three buttons.

a stand-in

The vibration

A computer has no vibration motor, so each vibration shakes the phone and writes a line in the Console (Haptics: notification success).

Smart QR home screen in Expo Go on an Android phone emulator: the QR logo, Smart QR, Scan a QR code and feel the result, Start scanning

The same project on a real Android phone (an emulator, in Expo Go). The files you write on this page run there unchanged.

The tests and the end-to-end flows run here too. On a computer they need Node, Java and an Android emulator; on this page:

On a computer, or on this page?
WhatOn a computerinstalled toolsOn this pagenothing to install
Run the unit and component testsnpm test in a terminal (Jest)the Run tests button: the same test files, the same output
Run a Maestro flowmaestro test flow.yaml with an emulator openthe Run flow button: the same YAML, played on this page’s phone
See the appExpo Go on a phone, or the Android emulatorthe phone next to the editorbetter here
Build the app file (APK)eas build sends the project to Expo’s serversyou prepare app.json and eas.json; Part 9 shows a real build

② How it works: Expo Go or your own build

On a real phone there are two ways to run Smart QR. Expo Go is quick while you write the app; your own build is the real app you give to others. This decides which settings are used — and Exercise 2 asks about it:

Expo Go or your own build?

your computer$ npx expo start$ eas buildApp.tsxsrc/…app.json
Expo Goone app from the storeruns your JavaScriptdialog: “Allow Expo Go …”
QRSmart QRyour own app fileyour name, icon, permission textJS → update · native → new build
  1. 1 / 5Expo Go: one app for every project

    Expo Go is an app from the store. It already has many native packages inside — the camera and haptics too. It does not know your project yet.

Expo Go or your own build?
WhatExpo Gofrom the storeYour own buildEAS Build
What it isOne app that runs any project’s JavaScriptYour app, with only the native code it needs
Native packagesOnly the ones inside Expo Go (expo-camera and expo-haptics are)Any package you add
app.json settings (icon, permission texts, plugins)Not used: Expo Go has its ownUsedbetter here
Your changesAppear at once (Fast Refresh)better hereJavaScript: with an update. Native: a new build
Share with othersThey need your computer runningInstall link, or the storesbetter here

Which one would you use?

  1. You are writing the scanner and want to see each change in a second.
  2. A classmate at home wants to try your app.
  3. You want your own text in the iPhone camera dialog.

③ The code, line by line: the finished files

Three files are finished — every screen uses them. Read them once; the phone shows what each part draws.

App.tsxFinished file · the two screensStep 1 of 6
import { useState } from 'react';
import { StatusBar } from 'expo-status-bar';
import HomeScreen from './src/screens/HomeScreen';
import ScannerScreen from './src/screens/ScannerScreen';
 
export default function App() {
  const [screen, setScreen] = useState<'home' | 'scanner'>('home');
 
  return (
    <>
      <StatusBar style="light" />
      {screen === 'home' ? (
        <HomeScreen onStart={() => setScreen('scanner')} />
      ) : (
        <ScannerScreen onBack={() => setScreen('home')} />
      )}
    </>
  );
}

On the lab phone now

The Smart QR home screenThe scanner screen asking for the camera
Console

Now explaining · lines 1–4React

Imports

Imports: useState from React, the StatusBar (the bar with the clock and battery), and the two screens of the app.

The app starts on the home screen.

src/components/AppButton.tsxFinished file · one button for the whole appStep 1 of 8
import { Pressable, StyleSheet, Text } from 'react-native';
 
type Props = {
  title: string;
  onPress: () => void;
  testID?: string;
  variant?: 'primary' | 'light';
};
 
export default function AppButton({ title, onPress, testID, variant = 'primary' }: Props) {
  return (
    <Pressable
      accessibilityRole="button"
      testID={testID}
      onPress={onPress}
      style={({ pressed }) => [styles.button, styles[variant], pressed && styles.pressed]}
    >
      <Text style={[styles.text, variant === 'light' && styles.lightText]}>{title}</Text>
    </Pressable>
  );
}
 
const styles = StyleSheet.create({
  button: { minHeight: 52, paddingHorizontal: 22, borderRadius: 14, alignItems: 'center', justifyContent: 'center' },
  primary: { backgroundColor: '#0EA5E9' },
  light: { backgroundColor: 'rgba(255,255,255,0.16)', borderWidth: 1, borderColor: 'rgba(255,255,255,0.35)' },
  pressed: { opacity: 0.75, transform: [{ scale: 0.98 }] },
  text: { color: '#FFFFFF', fontSize: 17, fontWeight: '700' },
  lightText: { fontWeight: '600' },
});

On the lab phone now

Allow camera (a primary button) and Back (a light button)The light buttons Back, Flip camera and Use sample QR
Console

Now explaining · line 1React Native

The building blocks

Pressable is a box that reacts to touches; Text shows the title; StyleSheet creates the styles.

Allow camera is a primary button, Back a light one.

src/screens/HomeScreen.tsxFinished file · the home screenStep 1 of 6
import { StyleSheet, Text, View } from 'react-native';
import AppButton from '../components/AppButton';
 
type Props = { onStart: () => void };
 
export default function HomeScreen({ onStart }: Props) {
  return (
    <View style={styles.screen}>
      <View style={styles.logo}>
        <Text style={styles.logoText}>QR</Text>
      </View>
      <Text style={styles.title}>Smart QR</Text>
      <Text style={styles.subtitle}>Scan a QR code and feel the result.</Text>
      <AppButton title="Start scanning" testID="start-scan" onPress={onStart} />
    </View>
  );
}
 
const styles = StyleSheet.create({
  screen: { flex: 1, backgroundColor: '#0F172A', alignItems: 'center', justifyContent: 'center', padding: 32, gap: 16 },
  logo: { width: 96, height: 96, borderRadius: 28, borderWidth: 4, borderColor: '#38BDF8', alignItems: 'center', justifyContent: 'center' },
  logoText: { color: '#38BDF8', fontSize: 34, fontWeight: '900' },
  title: { color: '#FFFFFF', fontSize: 36, fontWeight: '800' },
  subtitle: { color: '#CBD5E1', fontSize: 17, textAlign: 'center', marginBottom: 12 },
});

On the lab phone now

The Smart QR home screen
Console

Now explaining · lines 1–2React Native

Imports

React Native’s building blocks, and the app’s own button.

The screen this file draws.

④ Your turn · Exercise 2

You run Smart QR in Expo Go. Use the animation and the table above to choose what happens.

EX 02Expo Go or a new build?Loading the exercise…

Checkpoint

You know every part of the exercise screen, what runs on this page and what is a stand-in, and which settings Expo Go uses and which ones need your own build.

Part 3: Camera and haptics: how they work

16 min

Before you write the scanner in Part 4, see how its two packages behave: the camera permission, the live camera, and the vibrations. Two exercises at the end check that you can predict what they do.

A · The camera

① What you will see

A phone protects the camera: an app may use it only after the user says yes. The first time the app asks, the phone shows its own dialog. Your app cannot change its buttons; it can only read the answer.

Smart QR screen Camera permission needed, with the sentence Smart QR uses the camera only to read QR codes, an Allow camera button and a Back button

Your screen explains why

Android dialog Allow Expo Go to take pictures and record video? with the buttons While using the app, Only this time and Don’t allow

Then the phone asks

First your own screen says why the app needs the camera. Allow camera calls requestPermission(), and Android shows its dialog. In Expo Go the app asking is Expo Go, so the dialog says “Expo Go”.

② How it works: the permission

expo-camera gives a hook (a function that starts with use and can only run inside a component) for the permission:

const [permission, requestPermission]= useCameraPermissions();permissionpermission.grantedpermission.canAskAgainrequestPermission()
  1. const [permission, requestPermission]two values in an array, named by you
  2. = useCameraPermissions();the hook from expo-camera
  3. permissionnull at first (still asking the phone), then an object
  4. permission.grantedtrue when the user allowed the camera
  5. permission.canAskAgainfalse when the phone will not show the dialog again
  6. requestPermission()shows the phone’s dialog and gives back the new answer

Play the user. Each answer changes what the hook gives, and which part of the screen’s code runs:

What useCameraPermissions() gives

Which part of ScannerScreen draws the screen

  1. if (!permission) return <Text>Checking camera permission…</Text>;
  2. if (!permission.granted) return permission.canAskAgain
      ? <AppButton title="Allow camera" onPress={requestPermission} />
  3.   : <AppButton title="Open settings" onPress={() => Linking.openSettings()} />;
  4. return <CameraView … />;

● LIVE DEMOThe camera permission, step by stepLoading the editor and preview…

② How it works: CameraView, the live camera

CameraView is the component that shows the camera. Its props say what to do:

prop

facing='back'

Which camera: 'back' (default) or 'front'.

prop

barcodeScannerSettings={{ barcodeTypes: ['qr'] }}

Look for QR codes only. Without it the camera also reads other barcodes (EAN, Code 128, …).

prop

onBarcodeScanned={(scan) => …}

Runs each time a code is read. scan.data is the text inside the code, scan.type its kind ('qr').

prop

onMountError={(error) => …}

Runs when the camera cannot start (no permission, camera in use). error.message says why.

One important fact: the camera reads every frame it sees — many times a second. While a code is in front of it, onBarcodeScanned keeps running. Press the button below and switch the settings:

    handleScan worked

    —

    Vibrations the user feels

    —

    Press Hold a QR code in front of the camera.

    B · Haptics: feedback you feel

    ① What you will feel

    expo-haptics plays short vibrations. On the lab phone each one shakes the phone and names the pattern in the Console:

    ● recorded on this page
    Four patterns on the lab phone
    1. Success — the job worked. The Console says Haptics: notification success.
    2. Error — it did not work: a longer, stronger pattern.
    3. Selection — the lightest tap: a choice changed.
    4. Impact: Heavy — like a big object landing.

    ② How it works

    There are three kinds of call:

    an outcome

    notificationAsync(type)

    Success, Warning or Error: three different patterns. Smart QR uses Success and Error.

    a choice

    selectionAsync()

    The lightest tap: a choice changed. Smart QR uses it for Flip camera.

    a touch

    impactAsync(style)

    Like two objects touching: Light, Medium, Heavy, Rigid or Soft.

    Each call names its pattern with a value of the package:

    Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success)
    1. Haptics.notificationAsync(play an outcome pattern
    2. Haptics.NotificationFeedbackType.Successwhich one: Success, Warning or Error
    3. )it gives back a Promise — use await to wait until the phone has started it

    Two rules from Expo’s documentation shape Smart QR:

    • iPhones play no haptics while the camera is active (and none in Low Power Mode). So Smart QR vibrates on the result card, after the camera closed.
    • On Android, the vibration permission is added for you. Phones without a vibration motor throw an error, so every call is inside try / catch.

    Press each button, and change the code:

    ● LIVE DEMOEvery kind of haptic, one button eachLoading the editor and preview…

    ④ Your turn · Exercises 3 and 4

    Exercise 3 asks what the camera and the permission hook give your code — sections A and B above. Exercise 4 asks which vibration fits which moment.

    EX 03What does the camera give your code?Loading the exercise…
    EX 04Which vibration for which moment?Loading the exercise…

    Checkpoint

    You can name the three permission states, the four CameraView props Smart QR uses, why one code is read many times, and why Smart QR vibrates after the camera closes.

    Part 4: Build the scanner

    50 min

    In this part you write the scanner yourself, in four steps. Every step has the same four parts, always in this order — first you understand, then you write:

    ①

    What you will build

    Real pictures and a short recording of the lab phone: what the step adds.

    ②

    How it works

    An animation of what happens inside. Press Play, or go one step at a time with Next.

    ③

    The code, line by line

    The new code in colour, with the phone beside it. The lines you write are marked +.

    ④

    Your turn

    The exercise: write the code, try it on the phone, press Check.

    The four steps, and what the lab phone does after each one:

    After Step A: the lab phone shows Camera permission needed with an Allow camera button

    A · Ask for the camera

    After Step B: the result card with a green check, WEBSITE and https://expo.dev

    B · Read a code, once

    After Step C: the error card with a red mark, Can’t use this code and This QR code is empty

    C · Feel the result

    After Step D: the camera screen with the label Front camera

    D · Flip the camera

    Each step starts where the last one ended. All four steps change two files: src/screens/ScannerScreen.tsx (Steps A, B, D) and src/scan/feedback.ts (Step C).

    The packages this part uses:

    package · Steps A, B, D

    expo-camera

    useCameraPermissions asks the user for the camera. CameraView shows the camera and reads QR codes.

    package · Step C

    expo-haptics

    Short vibrations: a success pattern, an error pattern, and a small tap.

    React · every step

    useState · useRef · useEffect

    A value the screen remembers, a value that changes at once without drawing again, and code that runs after a screen appears.

    Step A · Ask for the camera

    ① What you will build

    Right now the scanner opens the camera without asking, so the lab phone shows “Camera error: Camera permission is not granted”. A phone protects its camera: an app may use it only after the user says yes. After this step, the scanner asks first — in four screens:

    The lab phone shows only the text Checking camera permission…

    1 · Checking…

    Camera permission needed, Smart QR uses the camera only to read QR codes, Allow camera and Back buttons

    2 · The app explains why

    The phone’s dialog: Allow this app to take pictures and record video? with While using the app, Only this time and Don’t allow

    3 · The phone asks

    The camera screen: Point the camera at a QR code, the blue frame with the sample codes, Back, Flip camera and Use sample QR

    4 · Allowed: the camera

    Screen 3 is the phone’s own dialog. Your app cannot change its buttons: it can only ask, and read the answer.

    The same path on the lab phone, as a recording:

    ● recorded on this page
    Step A on the lab phone
    1. The app starts on the home screen. The finger presses Start scanning.
    2. For a moment the screen says Checking camera permission… — the app is still asking the phone.
    3. The phone answers “not allowed yet”: the app shows Camera permission needed and Allow camera.
    4. Allow camera makes the phone show its own dialog.
    5. While using the app allows the camera: the camera opens, and the Console says Camera permission: allowed.

    When the user presses Don’t allow two times, Android never shows its dialog again. Then the app offers Open settings — the only way left to turn the camera on:

    Camera permission needed with an Open settings button instead of Allow camera

    After two refusals

    The lab phone’s Settings page for the camera: Allow only while using the app, Ask every time, Don’t allow, Back to the app

    Open settings → the Settings page

    ② How it works

    Three ideas explain the whole step:

    • A hook is a function whose name starts with use. React lets you call it only at the top of a component. useCameraPermissions() comes from expo-camera and tells your component what the user answered.
    • React runs your component again. A component is a function that React runs to draw the screen. When a hook or a state gets a new value, React runs the whole function again, from the first line.
    • The first return decides the screen. return ends a function. The first return that runs gives the screen; the lines under it do not run.

    Watch the three ideas work together. Press Play, or Next for one step at a time:

    How the screen picks what to draw

    permission =null (still asking the phone){ granted: false, canAskAgain: true }{ granted: false, canAskAgain: false }{ granted: true, … }
    ↻ runs again, from the top
    export default function ScannerScreen({ onBack }: Props) {  const [permission, requestPermission] = useCameraPermissions();  …  if (!permission) {    return <Text>Checking camera permission…</Text>;  }   if (!permission.granted) {    return (      <Text>Camera permission needed</Text> …      {permission.canAskAgain ? (        <AppButton title="Allow camera" onPress={requestPermission} />      ) : (        <AppButton title="Open settings" onPress={() => Linking.openSettings()} />      )}    );  }   if (result) { … }   // a scanned code: Step B  return <CameraView … />;}

    The phone shows what the first matching return gives.

    1. 1 / 6React runs your component from the top

      To draw the scanner, React runs ScannerScreen line by line, from the first line down. It stops at the first return it meets: what that return gives is the screen on the phone.

    ③ The code, line by line

    This is ScannerScreen.tsx after Step A. The lines marked + are the ones you write. Press Next: the lines light up, the phone shows what they do, and the text under the code explains them.

    src/screens/ScannerScreen.tsxStep A · ask for the cameraStep 1 of 9
    import { useRef, useState } from 'react';
    import { Linking, StyleSheet, Text, View } from 'react-native';
    import { CameraView, useCameraPermissions, type CameraType } from 'expo-camera';
    import { parseScan, type ScanResult } from '../scan/parseScan';
    import { tapFeedback } from '../scan/feedback';
    import AppButton from '../components/AppButton';
    import ResultCard from '../components/ResultCard';
    import ScanFrame from '../components/ScanFrame';
     
    // The fixed code the "Use sample QR" button sends, for tests (no real camera needed)
    export const SAMPLE_QR = 'https://expo.dev';
     
    type Props = { onBack: () => void };
     
    export default function ScannerScreen({ onBack }: Props) {
      const [permission, requestPermission] = useCameraPermissions();
      const [facing, setFacing] = useState<CameraType>('back');
      const [result, setResult] = useState<ScanResult | null>(null);
      const [cameraError, setCameraError] = useState<string | null>(null);
      // TODO Step B: a lock (useRef) so one QR code is handled only once
     
      function handleScan(data: string) {
        // TODO Step B: stop if the lock is closed, then close it
        console.log('Scanned:', data);
        setResult(parseScan(data));
      }
     
      function scanAgain() {
        // TODO Step B: open the lock again
        setResult(null);
      }
     
      function flipCamera() {
        // TODO Step D: a small tap (tapFeedback), then switch between 'back' and 'front'
      }
     
      if (!permission) {
        return (
          <View style={styles.center}>
            <Text style={styles.text}>Checking camera permission…</Text>
          </View>
        );
      }
     
      if (!permission.granted) {
        return (
          <View style={styles.center}>
            <Text style={styles.title}>Camera permission needed</Text>
            <Text style={styles.text}>Smart QR uses the camera only to read QR codes.</Text>
            {permission.canAskAgain ? (
              <AppButton title="Allow camera" testID="allow-camera" onPress={requestPermission} />
            ) : (
              <AppButton title="Open settings" testID="open-settings" onPress={() => Linking.openSettings()} />
            )}
            <AppButton title="Back" variant="light" onPress={onBack} />
          </View>
        );
      }
     
      if (result) {
        return <ResultCard result={result} onScanAgain={scanAgain} />;
      }
     
      return (
        <View style={styles.screen}>
          <CameraView
            style={styles.camera}
            facing={facing}
            /* TODO Step B: read only QR codes (barcodeScannerSettings), and send each scan to handleScan (onBarcodeScanned) */
            onMountError={(error) => setCameraError(error.message)}
          />
          <ScanFrame />
          <Text style={styles.hint}>Point the camera at a QR code</Text>
          {cameraError && <Text style={styles.error}>Camera error: {cameraError}</Text>}
          <View style={styles.controls}>
            <AppButton title="Back" variant="light" onPress={onBack} />
            <AppButton title="Flip camera" variant="light" testID="flip-camera" onPress={flipCamera} />
            {__DEV__ && <AppButton title="Use sample QR" variant="light" testID="sample-scan" onPress={() => handleScan(SAMPLE_QR)} />}
          </View>
        </View>
      );
    }
     
    const styles = StyleSheet.create({
      screen: { flex: 1, backgroundColor: '#000000' },
      camera: { flex: 1 },
      center: { flex: 1, backgroundColor: '#0F172A', alignItems: 'center', justifyContent: 'center', padding: 32, gap: 16 },
      title: { color: '#FFFFFF', fontSize: 24, fontWeight: '800', textAlign: 'center' },
      text: { color: '#CBD5E1', fontSize: 16, textAlign: 'center' },
      hint: { position: 'absolute', top: 72, alignSelf: 'center', color: '#FFFFFF', fontSize: 16, fontWeight: '600' },
      error: { position: 'absolute', top: 110, left: 24, right: 24, color: '#FCA5A5', textAlign: 'center' },
      controls: { position: 'absolute', bottom: 40, left: 16, right: 16, flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', gap: 10 },
    });
    

    On the lab phone now

    The Smart QR home screen with the Start scanning buttonChecking camera permission…Camera permission needed with the sentence Smart QR uses the camera only to read QR codesThe phone’s dialog over the app: While using the app, Only this time, Don’t allowCamera permission needed with Open settingsThe Settings page: Allow only while using the app, Ask every time, Don’t allowThe camera screen with the blue frame, the sample codes and the buttons
    Console

    Now explaining · line 3expo-camera

    Where the hook comes from

    This line is already in the file. It takes three names from the expo-camera package:

    • CameraView — the component that shows the camera.
    • useCameraPermissions — the hook that reads the camera permission and asks for it.
    • CameraType — a type with two values, 'back' and 'front'. The word type in front says it is used only by TypeScript, never when the app runs.

    Nothing changes on the screen: an import only makes names ready to use.

    ④ Your turn · Exercise 5

    In the exercise, ScannerScreen.tsx has three TODO Step A comments. They mark where the + lines go:

    1. Line 16: replace this comment with the hook line const [permission, requestPermission] = useCameraPermissions();
    2. Lines 37–38: replace these two comments with the two if blocks: “Checking…” and “Camera permission needed”

    Write the code, then try it on the phone: press Start scanning, answer the dialog, and also try Don’t allow two times. When it works, press Check — each green line is one thing that works.

    EX 05Step A · Ask for the cameraLoading the exercise…

    Step B · Read a code, once

    ① What you will build

    The camera opens now, but it reads nothing. After this step, a QR code in front of the camera opens the result card with what is inside it. On the lab phone the codes are buttons: QR: Website holds that code in front of the camera.

    ● recorded on this page
    Step B on the lab phone
    1. The camera is open. The finger presses QR: Website: that code is now “in front of the camera”.
    2. The result card opens: a green check, WEBSITE, and the text inside the code, https://expo.dev.
    3. The Console shows one line, Scanned: https://expo.dev — one code, one result.

    Each kind of code gives its own card:

    Result card WEBSITE https://expo.dev with Open link and Scan again

    QR: Website

    Result card TEXT Room 3.12 with Scan again

    QR: Text

    Result card WI-FI NETWORK showing the whole code WIFI:S:Lab-5G;T:WPA;P:secret123;; including the password

    QR: Wi-Fi — the password shows!

    Error card: Can’t use this code, This QR code is empty

    QR: Empty code

    Look at the Wi-Fi card: it shows the password (P:secret123). That is a real privacy bug — you fix it in Part 10.

    ② How it works

    A QR code holds only text: https://expo.dev, Room 3.12, or WIFI:S:Lab-5G;T:WPA;P:secret123;; (a Wi-Fi network). The camera reads that text and gives it to your code. This step solves two problems:

    1. The camera must look for QR codes, and send each one it reads to your function — two props of CameraView.
    2. The camera reads the same code again and again, as long as it is in front of the lens. One code must give one result.

    The second problem, and its fix — a lock — step by step:

    Why one QR code needs a lock

    const locked = useRef(false);    // the lock: false = open function handleScan(data: string) {  if (locked.current) return;    // closed? stop here  locked.current = true;         // close it  console.log('Scanned:', data);  setResult(parseScan(data));} function scanAgain() {  locked.current = false;        // open it again  setResult(null);}

    The same lock, made two ways — read 1 arrives, then read 2 a moment later:

    const [locked, setLocked] = useState(false)read 1 calls setLocked(true), but locked stays false until React draws the screen again → reads 2 and 3 pass too → 3 results ✕
    const locked = useRef(false)read 1 sets locked.current = true → it is true at once → read 2 stops on the first line → 1 result ✓
    locked.current = false · 🔓 openlocked.current = true · 🔒 closedno lock yet
    ConsoleScanned: https://expo.devScanned: https://expo.devScanned: https://expo.devScanned: https://expo.devScanned: https://expo.dev
    ✕ one code → 5 results, 5 vibrations✓ one code → one result
    1. 1 / 7The camera reads every frame

      A camera takes many pictures (frames) every second. While a QR code is in front of it, onBarcodeScanned runs for every frame that shows the code — here 5 reads in less than one second. Each read calls handleScan.

    Try it yourself: switch the lock off and on, press a code, and count the lines in the Console.

    ● LIVE DEMOWhy the scanner needs a lockLoading the editor and preview…

    handleScan turns the text into a result with parseScan, a finished file. Read what it gives for each code — the phone shows the card each result makes:

    src/scan/parseScan.tsFinished file · what is inside a QR codeStep 1 of 8
    // The kinds of QR content the app understands.
    export type ScanKind = 'website' | 'wifi' | 'email' | 'phone' | 'text';
     
    // A good scan has a kind, a label and the text. A bad scan has an error message.
    export type ScanResult =
      | { ok: true; kind: ScanKind; label: string; value: string }
      | { ok: false; error: string };
     
    const MAX_LENGTH = 500;
     
    export function parseScan(data: string | null | undefined): ScanResult {
      const value = (data ?? '').trim();
      const lower = value.toLowerCase();
     
      if (value === '') {
        return { ok: false, error: 'This QR code is empty.' };
      }
      if (value.length > MAX_LENGTH) {
        return { ok: false, error: 'This QR code is too long to show.' };
      }
      if (lower.startsWith('https://') || lower.startsWith('http://')) {
        return { ok: true, kind: 'website', label: 'Website', value };
      }
      if (lower.startsWith('wifi:')) {
        return { ok: true, kind: 'wifi', label: 'Wi-Fi network', value };
      }
      if (lower.startsWith('mailto:')) {
        return { ok: true, kind: 'email', label: 'Email', value };
      }
      if (lower.startsWith('tel:')) {
        return { ok: true, kind: 'phone', label: 'Phone number', value };
      }
      return { ok: true, kind: 'text', label: 'Text', value };
    }
    

    On the lab phone now

    Result card TEXT Room 3.12Error card: This QR code is emptyResult card WEBSITE https://expo.devResult card WI-FI NETWORK with the whole code and its password
    Console

    Now explaining · line 2

    Five kinds of content

    ScanKind lists the five kinds of content the app understands. A type made of fixed texts like this is a union: TypeScript allows only these five values.

    One kind of card per kind of content.

    On top of the camera the scanner draws the blue frame with the moving line — another finished file:

    src/components/ScanFrame.tsxFinished file · the scan frameStep 1 of 7
    import { useEffect, useRef } from 'react';
    import { Animated, StyleSheet, View } from 'react-native';
     
    const SIZE = 250;
     
    export default function ScanFrame() {
      const position = useRef(new Animated.Value(0)).current;
     
      useEffect(() => {
        const loop = Animated.loop(
          Animated.sequence([
            Animated.timing(position, { toValue: 1, duration: 1500, useNativeDriver: true }),
            Animated.timing(position, { toValue: 0, duration: 1500, useNativeDriver: true }),
          ]),
        );
        loop.start();
        return () => loop.stop();
      }, [position]);
     
      const translateY = position.interpolate({ inputRange: [0, 1], outputRange: [0, SIZE - 4] });
     
      return (
        <View style={styles.overlay}>
          <View style={styles.frame}>
            <View style={[styles.corner, styles.topLeft]} />
            <View style={[styles.corner, styles.topRight]} />
            <View style={[styles.corner, styles.bottomLeft]} />
            <View style={[styles.corner, styles.bottomRight]} />
            <Animated.View style={[styles.line, { transform: [{ translateY }] }]} />
          </View>
        </View>
      );
    }
     
    const styles = StyleSheet.create({
      overlay: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' },
      frame: { width: SIZE, height: SIZE },
      corner: { position: 'absolute', width: 44, height: 44, borderColor: '#38BDF8' },
      topLeft: { top: 0, left: 0, borderTopWidth: 5, borderLeftWidth: 5, borderTopLeftRadius: 18 },
      topRight: { top: 0, right: 0, borderTopWidth: 5, borderRightWidth: 5, borderTopRightRadius: 18 },
      bottomLeft: { bottom: 0, left: 0, borderBottomWidth: 5, borderLeftWidth: 5, borderBottomLeftRadius: 18 },
      bottomRight: { bottom: 0, right: 0, borderBottomWidth: 5, borderRightWidth: 5, borderBottomRightRadius: 18 },
      line: { position: 'absolute', left: 12, right: 12, height: 4, borderRadius: 2, backgroundColor: '#38BDF8' },
    });
    

    On the lab phone now

    The camera screen with the blue frame
    Console

    Now explaining · line 4React

    The size

    The frame is 250 × 250 points. (React Native measures in points, not pixels, so the frame has the same size on every phone.)

    The blue frame and its moving line.

    ③ The code, line by line

    ScannerScreen.tsx after Step B. Six new lines (+): two props for the camera and four for the lock.

    src/screens/ScannerScreen.tsxStep B · read a code, onceStep 1 of 8
    import { useRef, useState } from 'react';
    import { Linking, StyleSheet, Text, View } from 'react-native';
    import { CameraView, useCameraPermissions, type CameraType } from 'expo-camera';
    import { parseScan, type ScanResult } from '../scan/parseScan';
    import { tapFeedback } from '../scan/feedback';
    import AppButton from '../components/AppButton';
    import ResultCard from '../components/ResultCard';
    import ScanFrame from '../components/ScanFrame';
     
    // The fixed code the "Use sample QR" button sends, for tests (no real camera needed)
    export const SAMPLE_QR = 'https://expo.dev';
     
    type Props = { onBack: () => void };
     
    export default function ScannerScreen({ onBack }: Props) {
      const [permission, requestPermission] = useCameraPermissions();
      const [facing, setFacing] = useState<CameraType>('back');
      const [result, setResult] = useState<ScanResult | null>(null);
      const [cameraError, setCameraError] = useState<string | null>(null);
      const locked = useRef(false);
     
      function handleScan(data: string) {
        if (locked.current) return;
        locked.current = true;
        console.log('Scanned:', data);
        setResult(parseScan(data));
      }
     
      function scanAgain() {
        locked.current = false;
        setResult(null);
      }
     
      function flipCamera() {
        // TODO Step D: a small tap (tapFeedback), then switch between 'back' and 'front'
      }
     
      if (!permission) {
        return (
          <View style={styles.center}>
            <Text style={styles.text}>Checking camera permission…</Text>
          </View>
        );
      }
     
      if (!permission.granted) {
        return (
          <View style={styles.center}>
            <Text style={styles.title}>Camera permission needed</Text>
            <Text style={styles.text}>Smart QR uses the camera only to read QR codes.</Text>
            {permission.canAskAgain ? (
              <AppButton title="Allow camera" testID="allow-camera" onPress={requestPermission} />
            ) : (
              <AppButton title="Open settings" testID="open-settings" onPress={() => Linking.openSettings()} />
            )}
            <AppButton title="Back" variant="light" onPress={onBack} />
          </View>
        );
      }
     
      if (result) {
        return <ResultCard result={result} onScanAgain={scanAgain} />;
      }
     
      return (
        <View style={styles.screen}>
          <CameraView
            style={styles.camera}
            facing={facing}
            barcodeScannerSettings={{ barcodeTypes: ['qr'] }}
            onBarcodeScanned={(scan) => handleScan(scan.data)}
            onMountError={(error) => setCameraError(error.message)}
          />
          <ScanFrame />
          <Text style={styles.hint}>Point the camera at a QR code</Text>
          {cameraError && <Text style={styles.error}>Camera error: {cameraError}</Text>}
          <View style={styles.controls}>
            <AppButton title="Back" variant="light" onPress={onBack} />
            <AppButton title="Flip camera" variant="light" testID="flip-camera" onPress={flipCamera} />
            {__DEV__ && <AppButton title="Use sample QR" variant="light" testID="sample-scan" onPress={() => handleScan(SAMPLE_QR)} />}
          </View>
        </View>
      );
    }
     
    const styles = StyleSheet.create({
      screen: { flex: 1, backgroundColor: '#000000' },
      camera: { flex: 1 },
      center: { flex: 1, backgroundColor: '#0F172A', alignItems: 'center', justifyContent: 'center', padding: 32, gap: 16 },
      title: { color: '#FFFFFF', fontSize: 24, fontWeight: '800', textAlign: 'center' },
      text: { color: '#CBD5E1', fontSize: 16, textAlign: 'center' },
      hint: { position: 'absolute', top: 72, alignSelf: 'center', color: '#FFFFFF', fontSize: 16, fontWeight: '600' },
      error: { position: 'absolute', top: 110, left: 24, right: 24, color: '#FCA5A5', textAlign: 'center' },
      controls: { position: 'absolute', bottom: 40, left: 16, right: 16, flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', gap: 10 },
    });
    

    On the lab phone now

    The camera screenResult card WEBSITE https://expo.dev
    ConsoleCamera permission: allowed

    Now explaining · line 70expo-camera

    Look for QR codes only (you write this)

    A new prop of CameraView. Its value is an object, so it has two pairs of braces: the outer { } says “a JavaScript value comes here”, the inner { } is the object itself.

    barcodeTypes: ['qr'] — a list with one kind: QR codes. Without this prop the camera also reads the barcodes on products (EAN, Code 128, …).

    The camera looks for QR codes.

    ④ Your turn · Exercise 6

    The four TODO Step B comments in the exercise:

    1. Line 20: the lock — const locked = useRef(false);
    2. Line 23: if (locked.current) return; then locked.current = true;
    3. Line 29: locked.current = false;
    4. Line 69: the two camera props, barcodeScannerSettings and onBarcodeScanned

    Open the camera and press QR: Website. Watch the Console: each Scanned: line is one call of handleScan. With the lock there is exactly one. Then press Check.

    EX 06Step B · Read a code, onceLoading the exercise…

    Step C · Feel the result

    ① What you will build

    After a scan the phone should vibrate: a short success pattern for a good code, and an error pattern for a bad one. A computer has no vibration motor, so the lab phone shakes, and the Console names the pattern that played.

    ● recorded on this page
    Step C on the lab phone
    1. QR: Website — the result card opens and the phone shakes: Haptics: notification success.
    2. Scan again, then QR: Empty code — the error card opens.
    3. A different pattern plays: Haptics: notification error.
    The result card for a good code: a green check, WEBSITE, https://expo.dev

    Good code → Success

    The result card for a bad code: a red mark, Can’t use this code, This QR code is empty

    Bad code → Error

    Two patterns you can tell apart without looking at the screen: Success is short and light, Error is longer and stronger.

    ② How it works

    • expo-haptics plays the phone’s own vibration patterns (Part 3 showed all of them). Smart QR uses two: Success and Error.
    • async / await. Asking the phone to vibrate takes a moment. notificationAsync gives back a Promise — a value that is ready a little later. await waits for it, and await can only be used inside an async function.
    • try / catch. Some phones and tablets have no vibration motor; there the call throws an error. try { … } catch { … } catches the error, so the app keeps working.
    • When. iPhones switch haptics off while the camera is on. So Smart QR vibrates when the result card appears — after the camera has closed.

    When the phone vibrates

    // ScannerScreen.tsxsetResult(parseScan(data));if (result) return <ResultCard result={result} … />; // ResultCard.tsxuseEffect(() => {  if (result.ok) successFeedback();  else errorFeedback();}, [result]); // feedback.tsexport async function successFeedback() {  try {    await Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);  } catch {    // no vibration motor: the app still works  }}
    ConsoleScanned: https://expo.devHaptics: notification success
    1. 1 / 6The camera is on

      The scanner shows the camera. While the camera is active, an iPhone switches haptics off: a vibration asked for now is not felt. (Android would play it.)

    ③ The code, line by line

    src/scan/feedback.ts after Step C. You write the two functions at the top; the third one, tapFeedback, is finished — use it as your model.

    src/scan/feedback.tsStep C · feel the resultStep 1 of 5
    import * as Haptics from 'expo-haptics';
     
    // The phone's "success" vibration: the scan worked.
    export async function successFeedback() {
      try {
        await Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
      } catch {
        // A phone with no vibration motor: the app still works without it.
      }
    }
     
    // The phone's "error" vibration: the app cannot use this code.
    export async function errorFeedback() {
      try {
        await Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
      } catch {
        // No vibration motor: nothing to do.
      }
    }
     
    // A small tap for a button press, like flipping the camera.
    export async function tapFeedback() {
      try {
        await Haptics.selectionAsync();
      } catch {
        // No vibration motor: nothing to do.
      }
    }
    

    On the lab phone now

    The camera screenResult card WEBSITE https://expo.devError card: This QR code is empty
    ConsoleCamera permission: allowed

    Now explaining · line 1expo-haptics

    Everything from expo-haptics, in one name

    import * as Haptics puts everything the package exports into one object called Haptics: Haptics.notificationAsync, Haptics.NotificationFeedbackType, Haptics.selectionAsync, …

    Nothing to feel yet.

    Who calls these functions? ResultCard — a finished file — as soon as it appears:

    src/components/ResultCard.tsxFinished file · the result cardStep 1 of 9
    import { useEffect, useRef } from 'react';
    import { Animated, Linking, StyleSheet, Text, View } from 'react-native';
    import type { ScanResult } from '../scan/parseScan';
    import { errorFeedback, successFeedback } from '../scan/feedback';
    import AppButton from './AppButton';
     
    type Props = { result: ScanResult; onScanAgain: () => void };
     
    export default function ResultCard({ result, onScanAgain }: Props) {
      const appear = useRef(new Animated.Value(0)).current;
     
      useEffect(() => {
        // The camera is closed now, so the vibration also works on iPhone.
        if (result.ok) {
          successFeedback();
        } else {
          errorFeedback();
        }
        Animated.spring(appear, { toValue: 1, friction: 6, useNativeDriver: true }).start();
      }, [result, appear]);
     
      const scale = appear.interpolate({ inputRange: [0, 1], outputRange: [0.8, 1] });
     
      return (
        <View style={styles.screen}>
          <Animated.View style={[styles.card, { opacity: appear, transform: [{ scale }] }]}>
            <View style={[styles.badge, result.ok ? styles.good : styles.bad]}>
              <Text style={styles.badgeText}>{result.ok ? '✓' : '!'}</Text>
            </View>
            <Text style={styles.label}>{result.ok ? result.label : "Can't use this code"}</Text>
            <Text style={styles.value} selectable>
              {result.ok ? result.value : result.error}
            </Text>
            {result.ok && result.kind === 'website' && (
              <Text accessibilityRole="link" style={styles.link} onPress={() => Linking.openURL(result.value)} testID="open-link">
                Open link
              </Text>
            )}
            <AppButton title="Scan again" testID="scan-again" onPress={onScanAgain} />
          </Animated.View>
        </View>
      );
    }
     
    const styles = StyleSheet.create({
      screen: { flex: 1, backgroundColor: '#0F172A', alignItems: 'center', justifyContent: 'center', padding: 24 },
      card: { width: '100%', backgroundColor: '#FFFFFF', borderRadius: 24, padding: 24, gap: 14, alignItems: 'center' },
      badge: { width: 64, height: 64, borderRadius: 32, alignItems: 'center', justifyContent: 'center' },
      good: { backgroundColor: '#22C55E' },
      bad: { backgroundColor: '#EF4444' },
      badgeText: { color: '#FFFFFF', fontSize: 32, fontWeight: '800' },
      label: { fontSize: 14, fontWeight: '700', color: '#64748B', textTransform: 'uppercase', letterSpacing: 1 },
      value: { fontSize: 19, color: '#0F172A', textAlign: 'center' },
      link: { fontSize: 16, color: '#0284C7', fontWeight: '700', padding: 6 },
    });
    

    On the lab phone now

    Result card WEBSITE https://expo.devError card: Can’t use this code, This QR code is empty
    ConsoleScanned: https://expo.devHaptics: notification success

    Now explaining · lines 3–5React

    What the card uses

    The result’s type, the two vibrations you wrote in feedback.ts, and the app’s button.

    The card for a good code.

    ④ Your turn · Exercise 7

    The two TODO Step C comments in feedback.ts:

    1. Fill successFeedback with the try / await / catch of the success pattern
    2. Fill errorFeedback the same way, with Error

    Scan QR: Website, then QR: Empty code: the phone shakes, and the Console names each pattern. Then press Check.

    EX 07Step C · Feel the resultLoading the exercise…

    Step D · Flip the camera

    ① What you will build

    Flip camera switches between the back camera and the front camera, with a small tap you can feel.

    ● recorded on this page
    Step D on the lab phone
    1. The camera is open on the back camera.
    2. The finger presses Flip camera: a small tap (Haptics: selection), and the label says Front camera.
    3. A second press goes back to the back camera, with another tap.
    The camera screen with the label Back camera

    Back camera

    The camera screen with the label Front camera

    After Flip camera

    ② How it works

    A phone has two cameras: the back camera (for QR codes, documents, photos) and the front camera (for the user’s face). CameraView shows one of them, chosen by its prop facing: 'back' or 'front'.

    • facing is a state — a value the screen remembers (Lab 02: useState). Changing it with setFacing makes React run ScannerScreen again, and CameraView gets the new side.
    • The button does two things, in order: a small tap you can feel, then the switch.
    • The switch uses a function. setFacing can take the new value, or a function that gets the current value and returns the new one. The function form is safer: React always passes the newest value.

    Watch one press, step by step:

    Flip camera, step by step

    facing ='back''front'
    const [facing, setFacing] = useState<CameraType>('back'); function flipCamera() {  tapFeedback();  setFacing((current) => (current === 'back' ? 'front' : 'back'));} <CameraView facing={facing} … /><AppButton title="Flip camera" testID="flip-camera" onPress={flipCamera} />
    'back'→ (current) => current === 'back' ? 'front' : 'back' →'front'
    'front'→ (current) => current === 'back' ? 'front' : 'back' →'back'
    ConsoleHaptics: selectionHaptics: selection
    1. 1 / 5facing is a state

      useState<CameraType>('back') keeps which camera is on. It starts as 'back'. <CameraView facing={facing} /> reads it, so the phone shows the back camera.

    ③ The code, line by line

    The finished ScannerScreen.tsx. Step D adds two lines (+) inside flipCamera.

    src/screens/ScannerScreen.tsxStep D · flip the cameraStep 1 of 5
    import { useRef, useState } from 'react';
    import { Linking, StyleSheet, Text, View } from 'react-native';
    import { CameraView, useCameraPermissions, type CameraType } from 'expo-camera';
    import { parseScan, type ScanResult } from '../scan/parseScan';
    import { tapFeedback } from '../scan/feedback';
    import AppButton from '../components/AppButton';
    import ResultCard from '../components/ResultCard';
    import ScanFrame from '../components/ScanFrame';
     
    // The fixed code the "Use sample QR" button sends, for tests (no real camera needed)
    export const SAMPLE_QR = 'https://expo.dev';
     
    type Props = { onBack: () => void };
     
    export default function ScannerScreen({ onBack }: Props) {
      const [permission, requestPermission] = useCameraPermissions();
      const [facing, setFacing] = useState<CameraType>('back');
      const [result, setResult] = useState<ScanResult | null>(null);
      const [cameraError, setCameraError] = useState<string | null>(null);
      const locked = useRef(false);
     
      function handleScan(data: string) {
        if (locked.current) return;
        locked.current = true;
        console.log('Scanned:', data);
        setResult(parseScan(data));
      }
     
      function scanAgain() {
        locked.current = false;
        setResult(null);
      }
     
      function flipCamera() {
        tapFeedback();
        setFacing((current) => (current === 'back' ? 'front' : 'back'));
      }
     
      if (!permission) {
        return (
          <View style={styles.center}>
            <Text style={styles.text}>Checking camera permission…</Text>
          </View>
        );
      }
     
      if (!permission.granted) {
        return (
          <View style={styles.center}>
            <Text style={styles.title}>Camera permission needed</Text>
            <Text style={styles.text}>Smart QR uses the camera only to read QR codes.</Text>
            {permission.canAskAgain ? (
              <AppButton title="Allow camera" testID="allow-camera" onPress={requestPermission} />
            ) : (
              <AppButton title="Open settings" testID="open-settings" onPress={() => Linking.openSettings()} />
            )}
            <AppButton title="Back" variant="light" onPress={onBack} />
          </View>
        );
      }
     
      if (result) {
        return <ResultCard result={result} onScanAgain={scanAgain} />;
      }
     
      return (
        <View style={styles.screen}>
          <CameraView
            style={styles.camera}
            facing={facing}
            barcodeScannerSettings={{ barcodeTypes: ['qr'] }}
            onBarcodeScanned={(scan) => handleScan(scan.data)}
            onMountError={(error) => setCameraError(error.message)}
          />
          <ScanFrame />
          <Text style={styles.hint}>Point the camera at a QR code</Text>
          {cameraError && <Text style={styles.error}>Camera error: {cameraError}</Text>}
          <View style={styles.controls}>
            <AppButton title="Back" variant="light" onPress={onBack} />
            <AppButton title="Flip camera" variant="light" testID="flip-camera" onPress={flipCamera} />
            {__DEV__ && <AppButton title="Use sample QR" variant="light" testID="sample-scan" onPress={() => handleScan(SAMPLE_QR)} />}
          </View>
        </View>
      );
    }
     
    const styles = StyleSheet.create({
      screen: { flex: 1, backgroundColor: '#000000' },
      camera: { flex: 1 },
      center: { flex: 1, backgroundColor: '#0F172A', alignItems: 'center', justifyContent: 'center', padding: 32, gap: 16 },
      title: { color: '#FFFFFF', fontSize: 24, fontWeight: '800', textAlign: 'center' },
      text: { color: '#CBD5E1', fontSize: 16, textAlign: 'center' },
      hint: { position: 'absolute', top: 72, alignSelf: 'center', color: '#FFFFFF', fontSize: 16, fontWeight: '600' },
      error: { position: 'absolute', top: 110, left: 24, right: 24, color: '#FCA5A5', textAlign: 'center' },
      controls: { position: 'absolute', bottom: 40, left: 16, right: 16, flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', gap: 10 },
    });
    

    On the lab phone now

    The camera screen with Back cameraThe camera screen with Front camera
    ConsoleCamera permission: allowed

    Now explaining · line 17React

    The state: which camera is on

    useState<CameraType>('back') keeps which camera is on. It starts as 'back'. <CameraType> tells TypeScript the state can only be 'back' or 'front'.

    The back camera.

    ④ Your turn · Exercise 8

    The last TODO of the scanner, inside flipCamera:

    1. Line 35: tapFeedback(); then setFacing((current) => …)

    Replace the comment with the two lines. Then open the camera and press Flip camera two times: the label goes from Back camera to Front camera and back, and the Console shows one Haptics: selection line per press. Then press Check.

    EX 08Step D · Flip the cameraLoading the exercise…

    The finished scanner

    All four steps together. The whole file, one part at a time:

    src/screens/ScannerScreen.tsxThe finished scannerStep 1 of 14
    import { useRef, useState } from 'react';
    import { Linking, StyleSheet, Text, View } from 'react-native';
    import { CameraView, useCameraPermissions, type CameraType } from 'expo-camera';
    import { parseScan, type ScanResult } from '../scan/parseScan';
    import { tapFeedback } from '../scan/feedback';
    import AppButton from '../components/AppButton';
    import ResultCard from '../components/ResultCard';
    import ScanFrame from '../components/ScanFrame';
     
    // The fixed code the "Use sample QR" button sends, for tests (no real camera needed)
    export const SAMPLE_QR = 'https://expo.dev';
     
    type Props = { onBack: () => void };
     
    export default function ScannerScreen({ onBack }: Props) {
      const [permission, requestPermission] = useCameraPermissions();
      const [facing, setFacing] = useState<CameraType>('back');
      const [result, setResult] = useState<ScanResult | null>(null);
      const [cameraError, setCameraError] = useState<string | null>(null);
      const locked = useRef(false);
     
      function handleScan(data: string) {
        if (locked.current) return;
        locked.current = true;
        console.log('Scanned:', data);
        setResult(parseScan(data));
      }
     
      function scanAgain() {
        locked.current = false;
        setResult(null);
      }
     
      function flipCamera() {
        tapFeedback();
        setFacing((current) => (current === 'back' ? 'front' : 'back'));
      }
     
      if (!permission) {
        return (
          <View style={styles.center}>
            <Text style={styles.text}>Checking camera permission…</Text>
          </View>
        );
      }
     
      if (!permission.granted) {
        return (
          <View style={styles.center}>
            <Text style={styles.title}>Camera permission needed</Text>
            <Text style={styles.text}>Smart QR uses the camera only to read QR codes.</Text>
            {permission.canAskAgain ? (
              <AppButton title="Allow camera" testID="allow-camera" onPress={requestPermission} />
            ) : (
              <AppButton title="Open settings" testID="open-settings" onPress={() => Linking.openSettings()} />
            )}
            <AppButton title="Back" variant="light" onPress={onBack} />
          </View>
        );
      }
     
      if (result) {
        return <ResultCard result={result} onScanAgain={scanAgain} />;
      }
     
      return (
        <View style={styles.screen}>
          <CameraView
            style={styles.camera}
            facing={facing}
            barcodeScannerSettings={{ barcodeTypes: ['qr'] }}
            onBarcodeScanned={(scan) => handleScan(scan.data)}
            onMountError={(error) => setCameraError(error.message)}
          />
          <ScanFrame />
          <Text style={styles.hint}>Point the camera at a QR code</Text>
          {cameraError && <Text style={styles.error}>Camera error: {cameraError}</Text>}
          <View style={styles.controls}>
            <AppButton title="Back" variant="light" onPress={onBack} />
            <AppButton title="Flip camera" variant="light" testID="flip-camera" onPress={flipCamera} />
            {__DEV__ && <AppButton title="Use sample QR" variant="light" testID="sample-scan" onPress={() => handleScan(SAMPLE_QR)} />}
          </View>
        </View>
      );
    }
     
    const styles = StyleSheet.create({
      screen: { flex: 1, backgroundColor: '#000000' },
      camera: { flex: 1 },
      center: { flex: 1, backgroundColor: '#0F172A', alignItems: 'center', justifyContent: 'center', padding: 32, gap: 16 },
      title: { color: '#FFFFFF', fontSize: 24, fontWeight: '800', textAlign: 'center' },
      text: { color: '#CBD5E1', fontSize: 16, textAlign: 'center' },
      hint: { position: 'absolute', top: 72, alignSelf: 'center', color: '#FFFFFF', fontSize: 16, fontWeight: '600' },
      error: { position: 'absolute', top: 110, left: 24, right: 24, color: '#FCA5A5', textAlign: 'center' },
      controls: { position: 'absolute', bottom: 40, left: 16, right: 16, flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', gap: 10 },
    });
    

    On the lab phone now

    The home screenChecking camera permission…The result cardThe camera screenThe front cameraCamera permission needed
    Console

    Now explaining · lines 1–8React

    Imports

    React’s hooks, React Native’s parts, the camera (CameraView, useCameraPermissions and the CameraType type), the parser, the tap vibration, and the three components.

    The app starts on the home screen.

    The same scanner on a real Android phone (an emulator, in Expo Go):

    Smart QR scanning on an Android emulator: the camera shows a room, the blue frame and the hint Point the camera at a QR code

    Scanning

    The result card after the sample scan: WEBSITE https://expo.dev with Open link and Scan again

    One code, one result

    The Android emulator’s back camera shows a 3-D room. Real QR codes need a phone; on the emulator use Use sample QR.

    CheckpointBreak · 5 minutes

    Your scanner asks for the camera, reads a code once, vibrates on the result and flips the camera — and you know what every line does. Take a 5-minute break.

    Part 5: Testing: three tools, three layers

    14 min

    A test is code that runs part of your app and checks the result with an assertion (“I expect this to equal that”). When you change the app later, the tests run again in seconds and tell you if something that worked is now broken — a regression.

    ① What you will see

    On this page, Run tests runs the test files of the project and prints what npm test prints on a computer: one line per test, ✓ or ✕, and a summary.

    ● recorded on this page
    Run tests on the lab page
    1. The terminal panel shows the command it runs: npm test -- __tests__/parseScan-test.ts.
    2. The finger presses ▶ Run tests.
    3. Jest prints PASS, one green ✓ per test, and the summary: Tests: 7 passed, 7 total.

    ② How it works

    What Jest does when you press Run tests, one step at a time:

    What happens when you press Run tests

    the project

    • App.tsx
    • src/scan/parseScan.ts
    • __tests__/parseScan-test.ts
    • __tests__/ScannerScreen-test.tsx
    • .maestro/scan-sample.yaml
    test('a website link is a website', () => {  const result = parseScan('https://expo.dev');  expect(result).toEqual({ ok: true, kind: 'website', label: 'Website', value: 'https://expo.dev' });});
    received (your code gave){ ok: true, kind: 'website''text', … }
    expected (the test says){ ok: true, kind: 'website', … }
    equal → ✓ PASSdifferent → ✕ FAIL
    npm testRunning 2 test files…✓ a website link is a website✕ a website link is a websiteTests: 12 passed, 12 totalTime: 0.4 s
    1. 1 / 5Find the test files

      Jest looks through the project for test files: the files in a __tests__ folder, or whose name ends in -test.ts / .test.ts. The app’s own files and the Maestro flow are not tests for Jest.

    Tests come in layers. The lower the layer, the smaller the piece it runs, and the faster it is:

    ↑ more real, slower, fewer↓ faster, more of them

    What really runs
    One function (parseScan) with one input. No screen, no phone.
    What is fake
    Nothing to fake: parseScan only turns text into a result.
    Speed
    Fastest: milliseconds per test.
    Catches
    Wrong logic in one function: a kind, a label, an error message.
    In Smart QR
    __tests__/parseScan-test.ts
    Run it
    npm test

    One tool for each layer:

    runs the tests

    Jest

    Finds the test files (__tests__/…-test.ts), runs them in Node on your PC, prints PASS or FAIL. jest-expo sets it up for Expo and fakes the native parts.

    draws a screen

    React Native Testing Library

    Draws one component inside a Jest test, then finds things the way a user does (by text, by role) and presses them.

    drives the real app

    Maestro

    Taps through the real app on the emulator or a phone, from a list of steps in a YAML file.

    Each layer has a cost: unit tests are cheap but see little; the end-to-end test sees everything but is slow and needs an emulator. So an app has many unit tests, some component tests and few end-to-end flows. For a bug, the best test is the fastest one that can see it.

    ④ Your turn · Exercise 9

    Four bugs in Smart QR: drag the fastest test that catches each one.

    EX 09Which test catches this bug?Loading the exercise…

    Checkpoint

    For any bug you can say which test sees it first: a unit test, a component test, an end-to-end flow — or only a person with a phone.

    Part 6: Unit and component tests

    38 min

    A · How a project gets Jest

    On a computer, a new Expo project gets its test tools with these commands (from Expo’s guide; on macOS and Linux leave out the quotes around --). On this page they are ready: the Run tests button does what npm test does.

    A new project on a computer — set up the tests (Windows)
    npx expo install jest-expo jest @types/jest "--" --dev
    npx expo install @testing-library/react-native "--" --dev
    npm install --save-dev test-renderer
    then npm test runs every file in __tests__/
    package.jsonFinished file · packages and the test commandStep 1 of 9
    {
      "name": "smart-qr-scanner",
      "version": "1.0.0",
      "main": "index.ts",
      "dependencies": {
        "expo": "~58.0.26",
        "expo-camera": "~58.0.14",
        "expo-haptics": "~58.0.8",
        "expo-status-bar": "~58.0.5",
        "react": "19.3.0",
        "react-native": "0.88.1"
      },
      "devDependencies": {
        "@testing-library/react-native": "^14.1.0",
        "@types/jest": "^30.0.0",
        "@types/react": "~19.3.0",
        "jest": "~30.5.2",
        "jest-expo": "~58.0.15",
        "test-renderer": "^1.3.1",
        "typescript": "~6.0.3"
      },
      "scripts": {
        "start": "expo start",
        "android": "expo start --android",
        "ios": "expo start --ios",
        "web": "expo start --web",
        "test": "jest",
        "test:watch": "jest --watchAll"
      },
      "private": true,
      "jest": {
        "preset": "jest-expo"
      }
    }
    

    Now explaining · lines 5–12Expo

    dependencies: what the app needs on the phone

    dependencies go into the app. expo-camera and expo-haptics are here.

    tsconfig.jsonFinished file · TypeScript knows JestStep 1 of 3
    {
      "extends": "expo/tsconfig.base",
      "compilerOptions": {
        "strict": true,
        "types": ["jest"]
      }
    }
    

    Now explaining · line 2Expo

    Expo’s settings

    Start from Expo’s TypeScript settings.

    B · Unit tests: one function

    ① What you will see

    A unit test checks one function. Smart QR’s parseScan turns a code’s text into a result; seven tests check it, and all seven pass:

    The Run tests panel on the lab page: PASS __tests__/parseScan-test.ts, seven green ticks under parseScan, and Tests: 7 passed, 7 total

    The output of Run tests on this page — the same lines npm test prints on a computer.

    ② How it works

    A test file uses three words: describe groups tests, test is one test with a name, and expect(value) checks a value with a matcher such as .toEqual(…). The test calls your code like any other file, and compares what it gives with what it should give.

    ③ The code, line by line

    The output box beside the code shows what Jest prints for the line you are reading:

    __tests__/parseScan-test.tsSeven unit tests for parseScanStep 1 of 9
    import { parseScan } from '../src/scan/parseScan';
     
    describe('parseScan', () => {
      test('a website link is a website', () => {
        const result = parseScan('https://expo.dev');
        expect(result).toEqual({ ok: true, kind: 'website', label: 'Website', value: 'https://expo.dev' });
      });
     
      test('a Wi-Fi code is a Wi-Fi network', () => {
        const result = parseScan('WIFI:S:Lab-5G;T:WPA;P:secret123;;');
        expect(result.ok).toBe(true);
        if (result.ok) expect(result.kind).toBe('wifi');
      });
     
      test('email and phone codes are recognized', () => {
        expect(parseScan('mailto:ta@example.com')).toMatchObject({ ok: true, kind: 'email' });
        expect(parseScan('tel:+15555550100')).toMatchObject({ ok: true, kind: 'phone' });
      });
     
      test('anything else is plain text', () => {
        expect(parseScan('Room 3.12')).toMatchObject({ ok: true, kind: 'text', value: 'Room 3.12' });
      });
     
      test('spaces around the code are removed', () => {
        expect(parseScan('   https://expo.dev   ')).toMatchObject({ value: 'https://expo.dev' });
      });
     
      test('an empty code is an error', () => {
        expect(parseScan('')).toEqual({ ok: false, error: 'This QR code is empty.' });
        expect(parseScan('    ')).toEqual({ ok: false, error: 'This QR code is empty.' });
        expect(parseScan(null)).toEqual({ ok: false, error: 'This QR code is empty.' });
      });
     
      test('a very long code is an error', () => {
        const result = parseScan('x'.repeat(501));
        expect(result.ok).toBe(false);
      });
    });
    
    npm testPASS __tests__/parseScan-test.ts

    Now explaining · line 1Jest

    Import the code to test

    Tests import your code like any other file.

    Jest found the file and ran it.

    Run it yourself, then change one word of a test and run it again:

    ● LIVE DEMORun the unit tests, then break oneLoading the editor and preview…

    C · Read a failing test

    ② How it works

    A failing test is not bad news: it shows exactly where the code and the test disagree. This is real output from a computer, after one word of a test was changed:

    npm test on a computer
    npm test
    FAIL __tests__/parseScan-test.ts
    ● parseScan › an empty code is an error
     
    expect(received).toEqual(expected) // deep equality
     
    - Expected - 1
    + Received + 1
     
    Object {
    - "error": "The code is empty.",
    + "error": "This QR code is empty.",
    "ok": false,
    }
     
    28 | test('an empty code is an error', () => {
    > 29 | expect(parseScan('')).toEqual({ ok: false, error: 'The code is empty.' });
    | ^
     
    at Object.toEqual (__tests__/parseScan-test.ts:29:27)
     
    Test Suites: 1 failed, 1 passed, 2 total
    Tests: 1 failed, 11 passed, 12 total

    Read it in three places:

    1 · which test

    ● parseScan › an empty code is an error

    The group and the test name.

    2 · what differs

    − Expected · + Received

    − lines: what the test wanted. + lines: what your code gave.

    3 · where

    > 29 | … ^

    The line of the test file that failed, and the column (29:27).

    ④ Your turn · Exercise 10

    EX 10Read a failing testLoading the exercise…

    D · Write your own unit tests

    ② How it works

    Now you write tests yourself. A good test gives one input and expects the exact result — so it fails when the code breaks. How do you know your test is good enough? Check runs it on a broken copy of the code:

    How Check tests your tests

    your test checks…

    if (result.ok) expect(result.kind).toBe('wifi');expect(result.ok).toBe(true);
    Run 1 · the real parseScanreturn { ok: true, kind: 'wifi', label: 'Wi-Fi network', value };✓ PASS — must pass
    Run 2 · a broken copyreturn { ok: true, kind: 'text', label: 'Text', value };✕ FAIL — your test caught the bug ✓✓ PASS — the test cannot see the bug ✕
    1. 1 / 5You write a test for the Wi-Fi code

      Your test gives parseScan a Wi-Fi code and checks the answer. But is the check strong enough to notice a bug? Check finds out by running your tests twice.

    Choose the matcher by what you want to prove:

    the whole value

    toEqual(…)

    Every field must be the same: expect(parseScan('')).toEqual({ ok: false, error: 'This QR code is empty.' }).

    one value

    toBe(…)

    One value, like a kind: if (result.ok) expect(result.kind).toBe('wifi').

    some fields

    toMatchObject(…)

    Only the fields you list: toMatchObject({ ok: true, kind: 'email' }).

    ④ Your turn · Exercise 11

    Write two tests: a Wi-Fi code and an empty code. Check runs them on the real parseScan (they must pass) and on two broken copies (they must fail).

    EX 11Write the two missing unit testsLoading the exercise…

    E · Component tests: one screen

    ② How it works

    A component test draws one screen, with fakes for what a computer does not have: a camera and a vibration motor. jest.mock swaps a package for a fake one in one test file:

    jest.mock: fakes for a component test

    import { CameraView, useCameraPermissions } from 'expo-camera';
    expo-camerathe real package · needs a phone’s camera✕ no camera on a computer
    test-utils/fakeCamera.tsxthe fake · used only in this test filejest.mock('expo-camera', () => require('../test-utils/fakeCamera'));
    jest.mocked(useCameraPermissions).mockReturnValue([{ granted: true, … }, askForCamera]);jest.mock('expo-haptics');expect(Haptics.notificationAsync).toHaveBeenCalledWith(Haptics.NotificationFeedbackType.Success);
    Haptics.notificationAsync — calls remembered1 · NotificationFeedbackType.Success ✓
    1. 1 / 5A test runs on a computer

      ScannerScreen imports expo-camera. In a test there is no phone: no camera, no vibration motor. The real package cannot start, so the test needs a stand-in — a fake (a mock).

    ③ The code, line by line

    The fake camera — a finished file:

    test-utils/fakeCamera.tsxFinished file · a fake expo-cameraStep 1 of 5
    import { Pressable, Text, View } from 'react-native';
     
    // A fake expo-camera for tests: no real camera, and the test decides what is "scanned".
    export const useCameraPermissions = jest.fn();
     
    type Props = { onBarcodeScanned?: (scan: { type: string; data: string }) => void };
     
    export function CameraView({ onBarcodeScanned }: Props) {
      return (
        <View>
          <Pressable testID="fake-scan-website" onPress={() => onBarcodeScanned?.({ type: 'qr', data: 'https://expo.dev' })}>
            <Text>Fake scan: website</Text>
          </Pressable>
          <Pressable testID="fake-scan-empty" onPress={() => onBarcodeScanned?.({ type: 'qr', data: '   ' })}>
            <Text>Fake scan: empty code</Text>
          </Pressable>
        </View>
      );
    }
    
    what the test draws

    Now explaining · line 3Jest

    A stand-in for expo-camera

    This file pretends to be expo-camera in the tests. It exports the same names the scanner imports.

    The component test, test by test. The phone shows the screen the test draws; under it, what Jest prints:

    __tests__/ScannerScreen-test.tsxFive component tests for the scannerStep 1 of 15
    import { render, screen, userEvent } from '@testing-library/react-native';
    import { useCameraPermissions } from 'expo-camera';
    import * as Haptics from 'expo-haptics';
    import ScannerScreen from '../src/screens/ScannerScreen';
     
    jest.mock('expo-camera', () => require('../test-utils/fakeCamera'));
    jest.mock('expo-haptics');
     
    const askForCamera = jest.fn();
     
    function givePermission(permission: { granted: boolean; canAskAgain: boolean }) {
      jest.mocked(useCameraPermissions).mockReturnValue([permission as any, askForCamera, jest.fn()]);
    }
     
    beforeEach(() => {
      jest.clearAllMocks();
    });
     
    test('asks for the camera when permission is not granted yet', async () => {
      givePermission({ granted: false, canAskAgain: true });
      await render(<ScannerScreen onBack={jest.fn()} />);
     
      expect(screen.getByText('Camera permission needed')).toBeOnTheScreen();
     
      const user = userEvent.setup();
      await user.press(screen.getByRole('button', { name: 'Allow camera' }));
      expect(askForCamera).toHaveBeenCalledTimes(1);
    });
     
    test('sends the user to the settings when the phone will not ask again', async () => {
      givePermission({ granted: false, canAskAgain: false });
      await render(<ScannerScreen onBack={jest.fn()} />);
     
      expect(screen.getByRole('button', { name: 'Open settings' })).toBeOnTheScreen();
      expect(screen.queryByRole('button', { name: 'Allow camera' })).not.toBeOnTheScreen();
    });
     
    test('a scanned website shows its result and the success vibration', async () => {
      givePermission({ granted: true, canAskAgain: true });
      await render(<ScannerScreen onBack={jest.fn()} />);
     
      const user = userEvent.setup();
      await user.press(screen.getByTestId('fake-scan-website'));
     
      expect(await screen.findByText('https://expo.dev')).toBeOnTheScreen();
      expect(screen.getByText('Website')).toBeOnTheScreen();
      expect(Haptics.notificationAsync).toHaveBeenCalledWith(Haptics.NotificationFeedbackType.Success);
    });
     
    test('an empty code shows an error and the error vibration', async () => {
      givePermission({ granted: true, canAskAgain: true });
      await render(<ScannerScreen onBack={jest.fn()} />);
     
      const user = userEvent.setup();
      await user.press(screen.getByTestId('fake-scan-empty'));
     
      expect(await screen.findByText('This QR code is empty.')).toBeOnTheScreen();
      expect(Haptics.notificationAsync).toHaveBeenCalledWith(Haptics.NotificationFeedbackType.Error);
    });
     
    test('Scan again goes back to the camera', async () => {
      givePermission({ granted: true, canAskAgain: true });
      await render(<ScannerScreen onBack={jest.fn()} />);
     
      const user = userEvent.setup();
      await user.press(screen.getByTestId('fake-scan-website'));
      await user.press(await screen.findByRole('button', { name: 'Scan again' }));
     
      expect(screen.getByTestId('fake-scan-website')).toBeOnTheScreen();
    });
    

    On the lab phone now

    Nothing drawn yetCamera permission needed with Allow cameraCamera permission needed with Open settingsThe result card WEBSITE https://expo.devThe error card: This QR code is emptyThe camera screen again
    npm test

    Now explaining · line 1React Native Testing Library

    The tools of React Native Testing Library

    render draws a component, screen finds things on it, userEvent presses like a finger.

    Nothing is drawn yet.

    ④ Your turn · Exercise 12

    Each line of this test has one job: find, press or check. Match them.

    EX 12Find, press, check: the test toolsLoading the exercise…

    F · A component test, in order

    ② How it works

    The lines of a test must run in one order: arrange (prepare), act (do what a user does), assert (check). Watch one test run, line by line:

    One component test, line by line

    test('a scanned website shows its result and the success vibration', async () => {  givePermission({ granted: true, canAskAgain: true });  await render(<ScannerScreen onBack={jest.fn()} />);   const user = userEvent.setup();  await user.press(screen.getByTestId('fake-scan-website'));   expect(await screen.findByText('https://expo.dev')).toBeOnTheScreen();  expect(screen.getByText('Website')).toBeOnTheScreen();  expect(Haptics.notificationAsync).toHaveBeenCalledWith(Haptics.NotificationFeedbackType.Success);});
    ✓ PASS
    1. 1 / 6Arrange ① — the answer of the permission

      First, prepare the world of the test. givePermission makes the fake hook answer “granted”. It must come before render: the screen reads the permission while it is drawn.

    ④ Your turn · Exercise 13

    EX 13A component test, in orderLoading the exercise…

    G · Write your own component tests

    ② How it works

    Now add two component tests to ScannerScreen-test.tsx, with the tools above:

    • Refused for good: givePermission({ granted: false, canAskAgain: false }), render, then expect the Open settings button (getByRole('button', { name: 'Open settings' })).
    • An empty code: granted, render, press fake-scan-empty, wait for the error, then expect(Haptics.notificationAsync).toHaveBeenCalledWith(Haptics.NotificationFeedbackType.Error).

    The two screens your new tests draw and check — the same screens as on the lab phone:

    Camera permission needed with the Open settings button

    Test 1: refused for good

    The error card: Can’t use this code, This QR code is empty

    Test 2: an empty code

    Check runs them on the real screen (they must pass) and on two broken copies (they must fail), like Exercise 11.

    ④ Your turn · Exercise 14

    EX 14Write the two missing component testsLoading the exercise…

    Checkpoint

    Run tests shows 12 passed tests: 7 unit tests for parseScan and 5 component tests for the scanner, with a fake camera and fake haptics — and each new test fails on the bug it was written for.

    Part 7: Maestro: test the whole journey

    20 min

    Maestro drives the real app: it taps what a user taps and checks what a user sees. A test is a flow: a YAML file (a text format of name: value lines and - lists). Maestro finds elements by their text or by their id (your testID).

    ① What you will see

    On a computer, Maestro is a program that needs Java and an Android emulator. On this page, Run flow plays the same YAML file on the lab phone, step by step, and prints the steps the way Maestro does:

    ● recorded on this page
    Run flow on the lab page
    1. The finger presses ▶ Run flow.
    2. Nobody touches the phone: Maestro taps Start scanning, Allow camera, the dialog, and Use sample QR by itself.
    3. Each step is printed with COMPLETED. (This is the flow you finish in Exercise 16: the last checks are still missing.)

    ② How it works

    YAML in three rules: a key and its value with : (appId: host.exp.exponent); a list item starts with - (one step); and the spaces at the start of a line say what belongs to what (text: and optional: belong to the tapOn above them). Now watch the whole flow, one command at a time:

    A Maestro flow, one command at a time

    appId: host.exp.exponent---- stopApp- openLink: ${APP_URL}- extendedWaitUntil:    visible: "Start scanning"    timeout: 60000- tapOn: "Start scanning"- tapOn:    text: "Allow camera"    optional: true- tapOn:    text: "While using the app"    optional: true- tapOn:    id: "sample-scan"- assertVisible: "https://expo.dev"- assertVisible:    id: "scan-again"- takeScreenshot: scan-result
    maestro test .maestro/scan-sample.yamlRunning on BUENOVA phone > Flow scan-sampleStop host.exp.exponent... COMPLETEDOpen ${APP_URL}... COMPLETEDAssert that "Start scanning" is visible... COMPLETEDTap on "Start scanning"... COMPLETEDTap on (Optional) "Allow camera"... COMPLETEDTap on (Optional) "While using the app"... COMPLETEDTap on id: sample-scan... COMPLETEDAssert that "https://expo.dev" is visible... COMPLETEDAssert that id: scan-again is visible... COMPLETEDTake screenshot scan-result... COMPLETED
    1. 1 / 11Which app, then the steps

      appId names the app the flow drives. In Expo Go that is Expo Go itself: host.exp.exponent. The line --- ends the settings: every line below it is a step, a list item starting with -.

    ③ The code, line by line

    .maestro/scan-sample.yamlThe flow, command by commandStep 1 of 11
    appId: host.exp.exponent
    ---
    - stopApp
    - openLink: ${APP_URL}
    - extendedWaitUntil:
        visible: "Start scanning"
        timeout: 60000
    - tapOn: "Start scanning"
    - tapOn:
        text: "Allow camera"
        optional: true
    - tapOn:
        text: "While using the app"
        optional: true
    - tapOn:
        id: "sample-scan"
    - assertVisible: "https://expo.dev"
    - assertVisible:
        id: "scan-again"
    - takeScreenshot: scan-result
    

    On the lab phone now

    The home screenCamera permission neededThe camera screenThe result card
    maestro testRunning on BUENOVA phone > Flow scan-sample

    Now explaining · line 1Maestro

    appId: which app

    appId: which app the flow drives. In Expo Go, the app is Expo Go itself: host.exp.exponent.

    ④ Your turn · Exercise 15

    EX 15The Maestro flow, in orderLoading the exercise…

    Run a flow and read its output

    ② How it works

    Maestro prints one line per step. COMPLETED — done. WARNED — an optional step was skipped. FAILED — Maestro stops there and says why. The flow of Exercise 16 on the lab page, as far as the starter goes:

    The Run flow panel on the lab page: Running on BUENOVA phone, Flow scan-sample, and seven steps with COMPLETED up to Tap on id: sample-scan

    The starter flow stops after Use sample QR: the checks of the result are yours to write.

    The same flow on a real Android emulator, with the Maestro program on a computer (real output):

    maestro test on a computer
    maestro test .maestro/scan-sample.yaml -e APP_URL=exp://127.0.0.1:8081
    Running on Pixel_10_Pro_XL
    > Flow scan-sample
    Stop host.exp.exponent... COMPLETED
    Open ${APP_URL}... COMPLETED
    Assert that "Start scanning" is visible... COMPLETED
    Tap on "Start scanning"... COMPLETED
    Tap on (Optional) "Allow camera"... COMPLETED
    Tap on (Optional) "While using the app"... COMPLETED
    Tap on id: sample-scan... COMPLETED
    Assert that "https://expo.dev" is visible... COMPLETED
    Assert that id: scan-again is visible... COMPLETED
    Take screenshot scan-result... COMPLETED
    The screenshot Maestro saved at the end of the flow on the Android emulator: the result card with WEBSITE https://expo.dev and Scan again

    The picture takeScreenshot saved on the emulator. Maestro reached the result without a person touching the phone.

    When a step fails, Maestro stops and says which one. Real output, after the flow was copied to scan-fail.yaml with one line changed to expect https://expo.com:

    maestro test on a computer
    maestro test .maestro/scan-fail.yaml -e APP_URL=exp://127.0.0.1:8081
    > Flow scan-fail
    Tap on "Start scanning"... COMPLETED
    Tap on (Optional) "Allow camera"... WARNED
    Warning: Element not found: Text matching regex: Allow camera
    Tap on id: sample-scan... COMPLETED
    Assert that "https://expo.com" is visible... FAILED
    Assertion is false: "https://expo.com" is visible
    ==== Debug output (logs & screenshots) ====
    C:\Users\you\.maestro\tests\2026-11-23_200728

    WARNED is not a failure: the camera was already allowed, and the step was optional. FAILED is the real problem: the screen shows .dev, the flow expected .com.

    ④ Your turn · Exercise 16

    Finish the flow with the last three steps from the walk-through above (assertVisible twice and takeScreenshot), then press Run flow. Try a mistake too: change one letter of the text and run it again.

    EX 16Finish the flow and run itLoading the exercise…

    Checkpoint

    Your flow passes on the page’s phone, from a new phone to the result card — the same file that passed on a real Android emulator.

    Part 8: Deployment: EAS Build, Submit, Update

    17 min

    Expo Go runs your project only while your PC serves it. To give the app to others you need a build: the app file itself. EAS (Expo Application Services) does the work on Expo’s servers.

    ② How it works: builds

    Words for this part:

    • Binary — the installed app file: an APK (Android, installs with a tap), an AAB (Android App Bundle, the format Google Play wants) or an IPA (iPhone).
    • Signing — a digital signature that proves who made the app. Android uses a keystore (a file with your key). Every update must be signed with the same key.
    • Profile — a named set of build settings in eas.json: development, preview, production.
    • Internal distribution — sharing a build with a link instead of a store.
    • Update — new JavaScript sent to apps already installed (“over the air”), without a new binary.

    Choose a profile and a platform and follow the build:

    1. 1 · Your project
    2. 2 · Expo’s build server
    3. 3 · The file you get
    4. 4 · Where it goes

    The other road: eas update

    Only JavaScript or images changed? eas update --channel preview --message "Fix typo" --environment preview uploads the new JavaScript. Every installed build on the preview channel with the same runtime version downloads it the next time it opens. No new build, no store review. (Needs expo-updates in the build.)

    APK or AAB?
    WhatAPK.apkAAB.aab
    Install with a tapYesbetter hereNo
    Google Play accepts it for new appsNoYesbetter here
    Size on each phoneEverything for every phoneGoogle Play builds a smaller APK for each phonebetter here
    In Smart QRThe preview profileThe production profile

    Which one would you use?

    1. Your classmates test the app this week.
    2. The app goes to Google Play.

    ② How it works: Submit and Update

    eas submit uploads a finished production build to a store:

    Terminal — after a production build
    eas build --platform android --profile production
    eas submit --platform android
    or both in one: eas build --platform android --auto-submit
    Android

    Google Play

    A Google Play Developer account (one-time fee), the app created in the Play Console, and a Google service account key saved in Expo. The first submission goes to the internal testing track and stays a draft until the store listing is complete.

    iPhone

    App Store

    The Apple Developer Program (yearly fee). eas submit -p ios uploads to App Store Connect; after processing, the build appears in TestFlight for testers, then goes to App Review.

    Most changes are only JavaScript: a text, a style, a bug in parseScan. EAS Update sends them to every installed build without a new binary and without a store review:

    Terminal — once per project, then one command per update
    npx expo install expo-updates
    eas update:configure
    make a new build once (the build must contain expo-updates), then for each change:
    eas update --channel preview --message "Show the Wi-Fi name" --environment preview
    eas update--channel preview--message "…"--environment preview
    1. eas updateupload the JavaScript and images of the project
    2. --channel previewto the builds made with the preview profile
    3. --message "…"a note for you: what changed
    4. --environment previewwhich EAS environment variables to use (needed since SDK 55)

    The rule: an update reaches only builds with the same runtime version — the same native code. Watch both cases:

    EAS Update or a new build?

    the change

    src/scan/parseScan.ts (JavaScript)app.json · plugins / permission text (native)$ eas update --channel preview$ eas build --profile preview
    Expo’s serversupdate · runtime 1.0.0new build · runtime 1.1.0
    the app on a phone
    JavaScriptscreens, parseScan, styles✓ new parseScan, after a restartfrom the new build
    Native code · runtime 1.0.01.1.0camera, haptics, permission texts, icon✕ an update cannot change this✓ the new build is installed
    1. 1 / 5An installed build has two layers

      The app file on a phone has native code (Kotlin / Swift: the camera, the vibration motor, the permission texts, the icon) and JavaScript (your screens, parseScan, the styles). The native layer is fixed inside the file.

    ④ Your turn · Exercise 17

    EX 17eas update or a new build?Loading the exercise…

    The settings, line by line

    ③ The code, line by line

    eas.json holds the build profiles. eas build:configure writes the first version; Smart QR adds one line for the APK:

    eas.jsonFinished file · the build profilesStep 1 of 6
    {
      "cli": {
        "version": ">= 27.11.0",
        "appVersionSource": "remote"
      },
      "build": {
        "development": {
          "developmentClient": true,
          "distribution": "internal"
        },
        "preview": {
          "distribution": "internal",
          "android": {
            "buildType": "apk"
          }
        },
        "production": {
          "autoIncrement": true
        }
      },
      "submit": {
        "production": {}
      }
    }
    

    Now explaining · lines 2–5EAS

    The EAS CLI and the version numbers

    cli: the EAS CLI version this project needs, and appVersionSource: "remote": EAS keeps the build numbers on its servers.

    app.json describes the app itself: its name, its id in the stores, its icon. The plugins list lets a package change the native project when the app is built:

    app.jsonFinished file · the app and its camera pluginStep 1 of 9
    {
      "expo": {
        "name": "Smart QR",
        "slug": "smart-qr-scanner",
        "version": "1.0.0",
        "orientation": "portrait",
        "icon": "./assets/icon.png",
        "userInterfaceStyle": "dark",
        "ios": {
          "supportsTablet": true,
          "bundleIdentifier": "com.yourname.smartqr"
        },
        "android": {
          "adaptiveIcon": {
            "backgroundColor": "#E6F4FE",
            "foregroundImage": "./assets/android-icon-foreground.png",
            "backgroundImage": "./assets/android-icon-background.png",
            "monochromeImage": "./assets/android-icon-monochrome.png"
          },
          "predictiveBackGestureEnabled": false,
          "package": "com.yourname.smartqr",
          "permissions": [
            "android.permission.CAMERA"
          ]
        },
        "web": {
          "favicon": "./assets/favicon.png"
        },
        "plugins": [
          [
            "expo-camera",
            {
              "cameraPermission": "Allow $(PRODUCT_NAME) to use the camera to read QR codes.",
              "recordAudioAndroid": false
            }
          ]
        ]
      }
    }
    

    Now explaining · lines 3–5Expo

    Name, slug, version

    The app’s name on the phone (“Smart QR”), its short name in URLs (slug), and its version for users.

    Plugins run only when your own build is made. Expo Go was built long ago with its own settings, which is why the dialog in Expo Go names Expo Go (Part 2).

    ④ Your turn · Exercise 18

    EX 18What does each setting do?Loading the exercise…

    Checkpoint

    You can say what each profile builds, why the preview profile makes an APK and production an AAB, what signing is, and when eas update is enough.

    Part 9: EAS Build: configure and watch a real build

    16 min

    A build needs two things from the project: the app’s own id (in app.json) and the profiles (in eas.json). First you prepare both; then you follow a real build of Smart QR from start to install.

    A · Get the project ready

    ② How it works

    • The app’s id — ios.bundleIdentifier and android.package. Written like a reversed web address: com.yourname.smartqr, lowercase letters, numbers and dots. It must be the same on both platforms, unique in the stores, and it never changes after the first upload: change yourname now.
    • The preview profile — eas build:configure writes eas.json with three profiles. Smart QR’s preview profile needs "android": { "buildType": "apk" } (an APK, Part 8); production keeps the AAB and gets "autoIncrement": true.
    • Valid JSON — both files are JSON, and one comma in the wrong place stops the build. The four mistakes to avoid:

    The JSON rules, mistake by mistake

    "preview": {  "distribution": "internal",  "android": {    "buildType": "apk"  }}
    "preview": {  "distribution": "internal"  "android": {    "buildType": "apk"  }}
    "preview": {  "distribution": "internal",  "android": {    "buildType": "apk",  }}
    "preview": {  "distribution": "internal",  "android": {    "buildType": 'apk'  }}
    "preview": {  "distribution": "internal",  "android": {    buildType: "apk"  }}
    "preview": {  "distribution": "internal",  "android": {    "buildType": "apk"  }}
    ✓ valid JSON✕ Expected ',' or '}' after property value in JSON (line 3)✕ Expected double-quoted property name in JSON (line 5)✕ Unexpected token ''', …"ildType": 'apk' … is not valid JSON✕ Expected property name or '}' in JSON (line 4)
    • a , between items
    • no , after the last item
    • texts in " "
    • keys in " "
    1. 1 / 6The JSON shape

      JSON is text with strict rules: { } holds key: value pairs; every key and every text is in double quotes " "; a : between a key and its value; a , between two items — and none after the last one.

    ④ Your turn · Exercise 19

    EX 19Get the project ready for EAS BuildLoading the exercise…

    B · A real build, from command to install

    ① What you will see

    On a computer with Node, these are the commands that build it. eas-cli is installed once, and every student uses their own free account at expo.dev:

    On a computer — once per computer, then once per project
    npm install --global eas-cli
    eas login
    type your Expo email or username, then your password
    eas init
    creates the project on expo.dev and writes its id into app.json (extra.eas.projectId)
    eas build:configure
    writes eas.json with the development, preview and production profiles

    Then the build itself. These lines are real, from the build of Smart QR made for this lab (only the account name was changed):

    eas build on a computer
    eas build --platform android --profile preview
    Resolved "preview" environment for the build.
    No remote versions are configured for this project, versionCode will be initialized based on the value from the local project.
    √ Initialized versionCode with 1.
    √ Using remote Android credentials (Expo server)
    the first time EAS asks: Generate a new Android Keystore? → press Enter (Yes)
    - Generating keystore in the cloud...
    √ Created keystore
    Compressing project files and uploading to EAS Build.
    √ Uploaded to EAS 1s
    √ Computed project fingerprint
    See logs: https://expo.dev/accounts/your-account/projects/smart-qr-scanner/builds/…

    ② How it works

    What happened, in order:

    1. versionCode 1 — Android’s build number. EAS keeps it (appVersionSource: "remote").
    2. Keystore — EAS made the signing key and keeps it. Every later build is signed with it.
    3. Uploaded — the project (1.2 MB without node_modules) went to Expo’s servers.
    4. See logs — this link shows the build while it runs.

    The free plan waits in a queue: this build waited 38 minutes, then built in 8 minutes. When it is done, the link shows the build page. Opened on an Android phone, Install puts the app on it:

    The expo.dev page of the build: Build artifact APK, Android internal distribution build, an Install button and Succeeded

    Build artifact · APK · Succeeded. Anyone with the link can install it on Android. (The account name is blurred in this picture.)

    Smart QR running as its own app from the APK, without Expo Go: the home screen with Start scanning

    The installed APK: Smart QR is its own app now, with its own icon. No Expo Go, no computer. Use sample QR is gone too: __DEV__ is false in a build.

    ④ Your turn · Exercise 20

    EX 20What will this build give you?Loading the exercise…

    Checkpoint

    app.json has your app’s id and eas.json makes a preview APK: the two files a real eas build reads. You can say what each line of the build output means.

    Part 10: Final challenge and recap

    16 min

    ① What you will fix

    Scan the Wi-Fi code: the card shows the whole code — with the password. That is a real privacy bug: anyone who looks at the screen sees it. You fix it, then prove the fix with a test, like a real change.

    Before the fix: the Wi-Fi card shows the whole code WIFI:S:Lab-5G;T:WPA;P:secret123;; with the password

    Before: the password shows

    After the fix: the Wi-Fi card shows only the network name Lab-5G

    After: only the name

    ② How it works

    A Wi-Fi QR code is one text with fields cut by ;. Four string methods take the name out of it — one at a time:

    The Wi-Fi fix, one method at a time

    valueWIFI:S:Lab-5G;T:WPA;P:secret123;;
    fields'S:Lab-5G''T:WPA''P:secret123'''''
    nameField'S:Lab-5G'
    name'Lab-5G'
    WI-FI NETWORKWIFI:S:Lab-5G;T:WPA;P:secret123;;✕ the password is on the screen
    WI-FI NETWORKLab-5G✓ only the name
    1. 1 / 6What a Wi-Fi QR code holds

      One text, in a fixed format: WIFI: then fields cut by ;. S: is the network name, T: the security type, P: the password. Smart QR showed the whole text — with the password.

    ③ The code, line by line

    The Wi-Fi branch of parseScan.ts, fixed. The phone shows the card it makes:

    src/scan/parseScan.tsThe Wi-Fi branch, fixedStep 1 of 5
    if (lower.startsWith('wifi:')) {
      // "WIFI:S:Lab-5G;T:WPA;P:secret123;;" → the text after "WIFI:", cut at each ";"
      const fields = value.slice(5).split(';');
      // the field that starts with "S:" holds the network name ("S:Lab-5G")
      const nameField = fields.find((field) => field.startsWith('S:'));
      const name = nameField ? nameField.slice(2) : '';
      return { ok: true, kind: 'wifi', label: 'Wi-Fi network', value: name || 'Hidden network' };
    }
    

    On the lab phone now

    Before: the whole Wi-Fi code on the cardAfter: only Lab-5G on the card
    Console

    Now explaining · line 1React

    Only for Wi-Fi codes

    Only for Wi-Fi codes. A Wi-Fi QR code looks like WIFI:S:Lab-5G;T:WPA;P:secret123;;: S = the name, T = the security type, P = the password.

    Before the fix: the whole code, with the password.

    A fix is finished when a test proves it. Add this test to __tests__/parseScan-test.ts:

    __tests__/parseScan-test.tsThe test that proves the fixStep 1 of 3
    test('a Wi-Fi code shows the network name, never the password', () => {
      const result = parseScan('WIFI:S:Lab-5G;T:WPA;P:secret123;;');
      expect(result).toMatchObject({ ok: true, kind: 'wifi', value: 'Lab-5G' });
    });
    
    npm test

    Now explaining · line 1Jest

    Say what must happen

    The name says the rule: the network name, never the password.

    ④ Your turn · Exercise 21

    EX 21Final: the Wi-Fi name, never the passwordLoading the exercise…

    How does this fix reach phones that already have the app? Only parseScan.ts changed — JavaScript — so eas update is enough (Part 8), once the build contains expo-updates.

    What you can do now

    hardware

    Camera and haptics

    • ask for a permission and handle every answer
    • read QR codes once with a lock
    • vibrate at the right moment, on every phone
    testing

    Three layers

    • unit tests for logic (Jest)
    • component tests with fakes (React Native Testing Library)
    • an end-to-end flow (Maestro)
    deployment

    EAS

    • the app id and the profiles in eas.json, APK or AAB
    • signing with a keystore
    • submit to stores, update without a build

    Acceptance criteria

    Your Smart QR is complete when:

    • Start scanning shows “Checking camera permission…”, then asks; Don’t allow twice shows Open settings
    • One QR code gives one result (one Scanned: line) and one vibration
    • A good code plays the Success vibration, an empty code the Error vibration
    • Flip camera switches the camera with a small tap
    • A Wi-Fi code shows the network name and never the password
    • Run tests passes: 8 unit tests and 5 component tests, each new one failing on the bug it was written for
    • Run flow passes: the Maestro flow reaches the result card
    • app.json has your own id and eas.json makes a preview APK

    Questions to check yourself

    1. Why does useCameraPermissions() give null first, and what should the screen show then?
    2. What is the difference between canAskAgain: true and false, and what does the app show for each?
    3. Why is the scan lock a useRef and not a useState?
    4. Why does Smart QR play the success vibration in ResultCard and not in handleScan?
    5. Which test would you write first for a bug in parseScan? For a button that calls the wrong function? For a screen that never appears?
    6. In a Jest failure, which lines come from your code and which from the test?
    7. Why does the Maestro flow use optional: true for the permission dialog?
    8. When do you need a new build, and when is eas update enough?

    Later, to run Smart QR on your own computer and phone: the project is in smart-qr-starter.zip (npm install, then npx expo start, and Expo Go on the phone).

    CheckpointLab 07

    You built an app that uses the phone’s hardware, tested it on three levels, and prepared it for a real EAS build — all in the browser — and you know how to ship the next change.

    Expected result

    What you should see

    The Smart QR Scanner on the lab phone: it asks for the camera, reads a QR code once, shows what is inside it with a vibration, flips the camera, and never shows a Wi-Fi password. Run tests passes 13 tests, Run flow passes the Maestro flow, and app.json and eas.json are ready for an EAS build.

    Stuck?

    The camera opens but shows “Camera error: Camera permission is not granted”
    Cause

    The screen shows CameraView before the user allowed the camera.

    Fix

    Check the permission first: if (!permission) … (loading), if (!permission.granted) … (ask), and only then <CameraView /> (Part 4, Step A).

    Allow camera does nothing, and no dialog appears
    Cause

    The user refused twice before, so the phone no longer asks (canAskAgain is false) — or the button does not call requestPermission.

    Fix

    Show Open settings (Linking.openSettings()) when canAskAgain is false. On the lab phone, Open settings opens a Settings page where the camera can be allowed again.

    handleScan runs again and again for one QR code (several Scanned: lines)
    Cause

    The camera calls onBarcodeScanned for every frame that shows the code.

    Fix

    Add the lock: const locked = useRef(false);, then if (locked.current) return; locked.current = true; in handleScan, and locked.current = false; in scanAgain.

    Run tests: “Unable to find an element with text: …”
    Cause

    The words differ from the screen (a getBy query needs the whole text), or the element appears a moment later.

    Fix

    Copy the text from the phone exactly. For something that appears after a press, use await screen.findByText(…): it waits.

    Run tests: “Matcher error: received value must be a mock function”
    Cause

    toHaveBeenCalledWith was used on a real function: the package was not replaced by a mock.

    Fix

    Add jest.mock('expo-haptics'); at the top of the test file, or check a jest.fn().

    Check says “Your tests still pass on a broken …”
    Cause

    The test runs the code but does not check the part that broke.

    Fix

    Expect the exact value: toEqual the whole object, toBe('wifi') for the kind, toHaveBeenCalledWith(…Error) for the vibration.

    Run flow: “Element not found: Text matching regex: …”
    Cause

    Maestro matches the whole text of an element, and the words or letters differ.

    Fix

    Use the exact text from the screen, or tap by id: - tapOn: { id: "sample-scan" }.

    app.json or eas.json “is not valid JSON”
    Cause

    A missing comma or quote, or a comma after the last item.

    Fix

    Every key and text in double quotes; a comma between items, none after the last one.

    No vibration on an iPhone (in a real app)
    Cause

    iPhones turn haptics off while the camera is active, in Low Power Mode, and when System Haptics is off.

    Fix

    Play the vibration after the camera closes (Smart QR does it in ResultCard).

    Still stuck? Search the troubleshooting center or ask your TA.

    Resources

    End of lab · attendance

    Check in for Lab 07

    Checking whether check-in is open…