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):
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:
- The home screen. The finger presses Start scanning.
- The app asks for the camera: Allow camera, then the phone’s own dialog, While using the app.
- The camera opens. The lab phone has no real camera: the QR codes are buttons. The finger presses QR: Website.
- The result card: a green check, WEBSITE and
https://expo.dev. The phone vibrates — on the lab phone it shakes, and the Console saysHaptics: 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.
② 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-camerabring 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
expo-cameraShows the live camera and reads QR codes
expo-hapticsMakes the phone vibrate
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
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-camera now- 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.
- 2 / 5Hardware: the phone’s parts
Two packages your app imports.
expo-camerashows the camera and reads the codes;expo-hapticsplays short vibrations. A package brings the native code that talks to the phone’s hardware. - 3 / 5Testing: code that checks your code
Jest finds the test files, runs them on your computer and prints PASS or FAIL. React Native Testing Library draws one screen inside a Jest test. Maestro taps through the whole running app, like a person.
- 4 / 5Deployment: from your project to phones
Three services of EAS (Expo Application Services), all on Expo’s servers: Build makes the app file, Submit sends it to a store, Update sends new JavaScript to the apps people already installed.
- 5 / 5Not used any more: expo-barcode-scanner
You will find this package in old tutorials. It was removed from Expo: reading QR codes is now part of
expo-camera. Do not install it.
③ The project, file by file
The files with a ★ are the ones you write in this lab:
- 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.
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:
- The task: what to do, and how to try it on the phone.
- The checklist: what Check tests. Each line turns green when that part works.
- The files of the project. Click a tab to open a file.
- The editor: write your code here. The
TODOcomments show where. - The lab phone: it runs the code you write, while you type.
- The Console: what
console.logprints, the vibrations, and the camera’s answers. - Check: tests your work and says what is still missing.
- Reset: back to the starting code of the exercise.
- Hint: one hint at a time, when you are stuck.
- 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:
Your code
The same files, imports and packages (expo-camera, expo-haptics). What passes here runs unchanged in Expo Go.
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.
The vibration
A computer has no vibration motor, so each vibration shakes the phone and writes a line in the Console (Haptics: notification success).
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:
| What | On a computerinstalled tools | On this pagenothing to install |
|---|---|---|
| Run the unit and component tests | npm test in a terminal (Jest) | the Run tests button: the same test files, the same output |
| Run a Maestro flow | maestro test flow.yaml with an emulator open | the Run flow button: the same YAML, played on this page’s phone |
| See the app | Expo Go on a phone, or the Android emulator | the phone next to the editorbetter here |
| Build the app file (APK) | eas build sends the project to Expo’s servers | you 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?
$ npx expo start$ eas buildApp.tsxsrc/…app.json- 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.
- 2 / 5Your JavaScript comes from your computer
npx expo startserves your JavaScript. Expo Go downloads it and runs it, and reloads it in a second when you save a file (Fast Refresh). Your computer must stay on, on the same network. - 3 / 5Not your app.json settings
Expo Go was built long ago, with its own name, icon and permission texts. Your
app.jsonsettings and plugins are not used — that is why the camera dialog says “Expo Go”. - 4 / 5Your own build: your app file
EAS Build turns your project into your own app file (an APK on Android): your name, your icon, your permission text, the native packages you chose. It runs without your computer.
- 5 / 5Change it later: update or new build
New JavaScript (a text, a style, a bug fix) can reach your build with EAS Update. A new native package, permission text or icon needs a new build (Part 8).
| What | Expo Gofrom the store | Your own buildEAS Build |
|---|---|---|
| What it is | One app that runs any project’s JavaScript | Your app, with only the native code it needs |
| Native packages | Only 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 own | Usedbetter here |
| Your changes | Appear at once (Fast Refresh)better here | JavaScript: with an update. Native: a new build |
| Share with others | They need your computer running | Install link, or the storesbetter here |
Which one would you use?
- You are writing the scanner and want to see each change in a second.
Expo Go reloads your JavaScript at once.
- A classmate at home wants to try your app.
A build (an APK) runs without your computer.
- You want your own text in the iPhone camera dialog.
Permission texts come from app.json plugins, which only your own build uses.
③ 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.
1 import { useState } from 'react'; 2 import { StatusBar } from 'expo-status-bar'; 3 import HomeScreen from './src/screens/HomeScreen'; 4 import ScannerScreen from './src/screens/ScannerScreen'; 5 6 export default function App() { 7 const [screen, setScreen] = useState<'home' | 'scanner'>('home'); 8 9 return ( 10 <> 11 <StatusBar style="light" /> 12 {screen === 'home' ? ( 13 <HomeScreen onStart={() => setScreen('scanner')} /> 14 ) : ( 15 <ScannerScreen onBack={() => setScreen('home')} /> 16 )} 17 </> 18 ); 19 }
On the lab phone now


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.
Now explaining · line 6React
The app’s first component
export default makes this the app’s first component. Expo starts here (through index.ts).
Now explaining · line 7React
Which screen is open
A state that remembers which screen is open: 'home' or 'scanner'. It starts with 'home'.
Now explaining · line 11React Native
The status bar
style="light": white clock and battery icons, because the app is dark.
Now explaining · lines 12–13React
Home
If the state is 'home', show HomeScreen. Its onStart prop is a function that changes the state to 'scanner'.
Now explaining · lines 14–16React
Scanner
Otherwise show ScannerScreen. Its onBack prop goes back to 'home'. Two screens do not need a navigation library: one state is enough.
Start scanning changed the state: the scanner is open.
- lines 1–4 Imports
Imports:
useStatefrom React, theStatusBar(the bar with the clock and battery), and the two screens of the app. - line 6 The app’s first component
export defaultmakes this the app’s first component. Expo starts here (throughindex.ts). - line 7 Which screen is open
A state that remembers which screen is open:
'home'or'scanner'. It starts with'home'. - line 11 The status bar
style="light": white clock and battery icons, because the app is dark. - lines 12–13 Home
If the state is
'home', show HomeScreen. ItsonStartprop is a function that changes the state to'scanner'. - lines 14–16 Scanner
Otherwise show ScannerScreen. Its
onBackprop goes back to'home'. Two screens do not need a navigation library: one state is enough.
1 import { Pressable, StyleSheet, Text } from 'react-native'; 2 3 type Props = { 4 title: string; 5 onPress: () => void; 6 testID?: string; 7 variant?: 'primary' | 'light'; 8 }; 9 10 export default function AppButton({ title, onPress, testID, variant = 'primary' }: Props) { 11 return ( 12 <Pressable 13 accessibilityRole="button" 14 testID={testID} 15 onPress={onPress} 16 style={({ pressed }) => [styles.button, styles[variant], pressed && styles.pressed]} 17 > 18 <Text style={[styles.text, variant === 'light' && styles.lightText]}>{title}</Text> 19 </Pressable> 20 ); 21 } 22 23 const styles = StyleSheet.create({ 24 button: { minHeight: 52, paddingHorizontal: 22, borderRadius: 14, alignItems: 'center', justifyContent: 'center' }, 25 primary: { backgroundColor: '#0EA5E9' }, 26 light: { backgroundColor: 'rgba(255,255,255,0.16)', borderWidth: 1, borderColor: 'rgba(255,255,255,0.35)' }, 27 pressed: { opacity: 0.75, transform: [{ scale: 0.98 }] }, 28 text: { color: '#FFFFFF', fontSize: 17, fontWeight: '700' }, 29 lightText: { fontWeight: '600' }, 30 });
On the lab phone now


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.
Now explaining · lines 3–8React
The props
The props: a title, an onPress function, an optional testID, and a variant (primary blue or light see-through). The ? means optional.
Now explaining · line 10React
A default variant
The props are taken out of the object. variant = 'primary' is the default when no variant is given.
Now explaining · line 13React Native
A real button for screen readers — and tests
accessibilityRole="button": screen readers say “button”. Tests find it the same way: getByRole('button', { name: 'Allow camera' }) (Part 6).
Now explaining · line 14React Native
A name only tests see
testID: a name only tests can see. Maestro taps id: "sample-scan" and Jest reads getByTestId(…) with it.
Now explaining · line 16React Native
The style while pressed
The style is a function: React Native gives pressed, true while the finger is down. The array joins the base style, the variant’s style and the pressed style.
Three light buttons on the camera screen.
Now explaining · line 18React Native
The title
The title. A light button gets a lighter font weight.
Now explaining · lines 23–30React Native
The styles
The styles, created once with StyleSheet.create. styles[variant] picks styles.primary or styles.light.
- line 1 The building blocks
Pressableis a box that reacts to touches;Textshows the title;StyleSheetcreates the styles. - lines 3–8 The props
The props: a
title, anonPressfunction, an optionaltestID, and avariant(primaryblue orlightsee-through). The?means optional. - line 10 A default variant
The props are taken out of the object.
variant = 'primary'is the default when no variant is given. - line 13 A real button for screen readers — and tests
accessibilityRole="button": screen readers say “button”. Tests find it the same way:getByRole('button', { name: 'Allow camera' })(Part 6). - line 14 A name only tests see
testID: a name only tests can see. Maestro tapsid: "sample-scan"and Jest readsgetByTestId(…)with it. - line 16 The style while pressed
The style is a function: React Native gives
pressed, true while the finger is down. The array joins the base style, the variant’s style and the pressed style. - line 18 The title
The title. A light button gets a lighter font weight.
- lines 23–30 The styles
The styles, created once with
StyleSheet.create.styles[variant]picksstyles.primaryorstyles.light.
1 import { StyleSheet, Text, View } from 'react-native'; 2 import AppButton from '../components/AppButton'; 3 4 type Props = { onStart: () => void }; 5 6 export default function HomeScreen({ onStart }: Props) { 7 return ( 8 <View style={styles.screen}> 9 <View style={styles.logo}> 10 <Text style={styles.logoText}>QR</Text> 11 </View> 12 <Text style={styles.title}>Smart QR</Text> 13 <Text style={styles.subtitle}>Scan a QR code and feel the result.</Text> 14 <AppButton title="Start scanning" testID="start-scan" onPress={onStart} /> 15 </View> 16 ); 17 } 18 19 const styles = StyleSheet.create({ 20 screen: { flex: 1, backgroundColor: '#0F172A', alignItems: 'center', justifyContent: 'center', padding: 32, gap: 16 }, 21 logo: { width: 96, height: 96, borderRadius: 28, borderWidth: 4, borderColor: '#38BDF8', alignItems: 'center', justifyContent: 'center' }, 22 logoText: { color: '#38BDF8', fontSize: 34, fontWeight: '900' }, 23 title: { color: '#FFFFFF', fontSize: 36, fontWeight: '800' }, 24 subtitle: { color: '#CBD5E1', fontSize: 17, textAlign: 'center', marginBottom: 12 }, 25 });
On the lab phone now

Now explaining · lines 1–2React Native
Imports
React Native’s building blocks, and the app’s own button.
The screen this file draws.
Now explaining · line 4React
One prop
The only prop: onStart, a function with no arguments that returns nothing (() => void).
Now explaining · lines 8–15React Native
A column in the middle
A column in the middle of the screen: the logo, the title, one sentence, and the button.
Now explaining · lines 9–11React Native
The logo
The logo: a square with a blue border and the letters QR.
Now explaining · line 14React
Start scanning
Pressing Start scanning calls onStart, which App.tsx gave: the app switches to the scanner. testID="start-scan" is for tests.
Now explaining · lines 19–25React Native
The styles
flex: 1 fills the screen; alignItems and justifyContent: 'center' put the content in the middle; gap: 16 leaves 16 points between the items.
- lines 1–2 Imports
React Native’s building blocks, and the app’s own button.
- line 4 One prop
The only prop:
onStart, a function with no arguments that returns nothing (() => void). - lines 8–15 A column in the middle
A column in the middle of the screen: the logo, the title, one sentence, and the button.
- lines 9–11 The logo
The logo: a square with a blue border and the letters QR.
- line 14 Start scanning
Pressing Start scanning calls
onStart, which App.tsx gave: the app switches to the scanner.testID="start-scan"is for tests. - lines 19–25 The styles
flex: 1fills the screen;alignItemsandjustifyContent: 'center'put the content in the middle;gap: 16leaves 16 points between the items.
④ Your turn · Exercise 2
You run Smart QR in Expo Go. Use the animation and the table above to choose what happens.
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.
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]two values in an array, named by you= useCameraPermissions();the hook from expo-camerapermissionnull at first (still asking the phone), then an objectpermission.grantedtrue when the user allowed the camerapermission.canAskAgainfalse when the phone will not show the dialog againrequestPermission()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
if (!permission) return <Text>Checking camera permission…</Text>;
if (!permission.granted) return permission.canAskAgain ? <AppButton title="Allow camera" onPress={requestPermission} />: <AppButton title="Open settings" onPress={() => Linking.openSettings()} />;return <CameraView … />;
② How it works: CameraView, the live camera
CameraView is the component that shows the camera. Its props say what to do:
facing='back'
Which camera: 'back' (default) or 'front'.
barcodeScannerSettings={{ barcodeTypes: ['qr'] }}
Look for QR codes only. Without it the camera also reads other barcodes (EAN, Code 128, …).
onBarcodeScanned={(scan) => …}
Runs each time a code is read. scan.data is the text inside the code, scan.type its kind ('qr').
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:
- Success — the job worked. The Console says
Haptics: notification success. - Error — it did not work: a longer, stronger pattern.
- Selection — the lightest tap: a choice changed.
- Impact: Heavy — like a big object landing.
② How it works
There are three kinds of call:
notificationAsync(type)
Success, Warning or Error: three different patterns. Smart QR uses Success and Error.
selectionAsync()
The lightest tap: a choice changed. Smart QR uses it for Flip camera.
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(play an outcome patternHaptics.NotificationFeedbackType.Successwhich one: Success, Warning or Error)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:
④ 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.
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:
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:
expo-camera
useCameraPermissions asks the user for the camera. CameraView shows the camera and reads QR codes.
expo-haptics
Short vibrations: a success pattern, an error pattern, and a small tap.
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:
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:
- The app starts on the home screen. The finger presses Start scanning.
- For a moment the screen says Checking camera permission… — the app is still asking the phone.
- The phone answers “not allowed yet”: the app shows Camera permission needed and Allow camera.
- Allow camera makes the phone show its own dialog.
- 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:
② 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 fromexpo-cameraand 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
returndecides the screen.returnends a function. The firstreturnthat 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
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 / 6React runs your component from the top
To draw the scanner, React runs
ScannerScreenline by line, from the first line down. It stops at the firstreturnit meets: what thatreturngives is the screen on the phone. - 2 / 6First run:
permissionisnullThe hook is still asking the phone, so it gives
null(no value yet).!permissionmeans “there is no value” → true. So the firstreturnruns: the phone shows Checking camera permission…. The lines under it do not run. - 3 / 6A new value → React runs it again
The phone answers: not allowed yet, but it may ask. The hook gets this new value, and a new value makes React run
ScannerScreenagain, from the top. Nowpermissionis an object, so!permissionis false: thisifis skipped. - 4 / 6
!permission.grantedis true → askgrantedisfalse, so!permission.grantedis true and thisreturnruns. Inside it,canAskAgain ? A : Bpicks A becausecanAskAgainis true: the Allow camera button. Pressing it callsrequestPermission, and the phone shows its dialog. - 5 / 6Refused twice → Open settings
After two Don’t allow, Android stops asking:
canAskAgainis false. The samereturnruns, but? :now picks the part after:— the Open settings button. Only the phone’s Settings can turn the camera on now. - 6 / 6Allowed → the camera
The user allowed the camera:
grantedis true. Bothifs are skipped, there is no result yet, and the lastreturndraws the camera. The order of theifs is the order of the questions.
③ 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.
1 import { useRef, useState } from 'react'; 2 import { Linking, StyleSheet, Text, View } from 'react-native'; 3 import { CameraView, useCameraPermissions, type CameraType } from 'expo-camera'; 4 import { parseScan, type ScanResult } from '../scan/parseScan'; 5 import { tapFeedback } from '../scan/feedback'; 6 import AppButton from '../components/AppButton'; 7 import ResultCard from '../components/ResultCard'; 8 import ScanFrame from '../components/ScanFrame'; 9 10 // The fixed code the "Use sample QR" button sends, for tests (no real camera needed) 11 export const SAMPLE_QR = 'https://expo.dev'; 12 13 type Props = { onBack: () => void }; 14 15 export default function ScannerScreen({ onBack }: Props) { 16+ const [permission, requestPermission] = useCameraPermissions(); 17 const [facing, setFacing] = useState<CameraType>('back'); 18 const [result, setResult] = useState<ScanResult | null>(null); 19 const [cameraError, setCameraError] = useState<string | null>(null); 20 // TODO Step B: a lock (useRef) so one QR code is handled only once 21 22 function handleScan(data: string) { 23 // TODO Step B: stop if the lock is closed, then close it 24 console.log('Scanned:', data); 25 setResult(parseScan(data)); 26 } 27 28 function scanAgain() { 29 // TODO Step B: open the lock again 30 setResult(null); 31 } 32 33 function flipCamera() { 34 // TODO Step D: a small tap (tapFeedback), then switch between 'back' and 'front' 35 } 36 37+ if (!permission) { 38+ return ( 39+ <View style={styles.center}> 40+ <Text style={styles.text}>Checking camera permission…</Text> 41+ </View> 42+ ); 43+ } 44 45+ if (!permission.granted) { 46+ return ( 47+ <View style={styles.center}> 48+ <Text style={styles.title}>Camera permission needed</Text> 49+ <Text style={styles.text}>Smart QR uses the camera only to read QR codes.</Text> 50+ {permission.canAskAgain ? ( 51+ <AppButton title="Allow camera" testID="allow-camera" onPress={requestPermission} /> 52+ ) : ( 53+ <AppButton title="Open settings" testID="open-settings" onPress={() => Linking.openSettings()} /> 54+ )} 55+ <AppButton title="Back" variant="light" onPress={onBack} /> 56+ </View> 57+ ); 58+ } 59 60 if (result) { 61 return <ResultCard result={result} onScanAgain={scanAgain} />; 62 } 63 64 return ( 65 <View style={styles.screen}> 66 <CameraView 67 style={styles.camera} 68 facing={facing} 69 /* TODO Step B: read only QR codes (barcodeScannerSettings), and send each scan to handleScan (onBarcodeScanned) */ 70 onMountError={(error) => setCameraError(error.message)} 71 /> 72 <ScanFrame /> 73 <Text style={styles.hint}>Point the camera at a QR code</Text> 74 {cameraError && <Text style={styles.error}>Camera error: {cameraError}</Text>} 75 <View style={styles.controls}> 76 <AppButton title="Back" variant="light" onPress={onBack} /> 77 <AppButton title="Flip camera" variant="light" testID="flip-camera" onPress={flipCamera} /> 78 {__DEV__ && <AppButton title="Use sample QR" variant="light" testID="sample-scan" onPress={() => handleScan(SAMPLE_QR)} />} 79 </View> 80 </View> 81 ); 82 } 83 84 const styles = StyleSheet.create({ 85 screen: { flex: 1, backgroundColor: '#000000' }, 86 camera: { flex: 1 }, 87 center: { flex: 1, backgroundColor: '#0F172A', alignItems: 'center', justifyContent: 'center', padding: 32, gap: 16 }, 88 title: { color: '#FFFFFF', fontSize: 24, fontWeight: '800', textAlign: 'center' }, 89 text: { color: '#CBD5E1', fontSize: 16, textAlign: 'center' }, 90 hint: { position: 'absolute', top: 72, alignSelf: 'center', color: '#FFFFFF', fontSize: 16, fontWeight: '600' }, 91 error: { position: 'absolute', top: 110, left: 24, right: 24, color: '#FCA5A5', textAlign: 'center' }, 92 controls: { position: 'absolute', bottom: 40, left: 16, right: 16, flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', gap: 10 }, 93 });
On the lab phone now







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 wordtypein 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.
Now explaining · line 16expo-camera
Read the permission (you write this)
The first line you write, at the top of the component. useCameraPermissions() gives back two things in an array. The square brackets on the left take them out and give each one a name:
permission— what the phone has answered so far.requestPermission— a function. Calling it makes the phone show its permission dialog.
You choose the two names, but the order is fixed: first the answer, then the function. At the very start permission is null — the hook is still asking the phone.
At the very start the hook has no answer yet.
Now explaining · lines 37–43React
No answer yet: show “Checking camera permission…”
! means not. !permission is true when permission has no value yet (null). Then this return gives a small screen with one text.
Because return ends the function, nothing below this block runs while permission is null. That matters: the next block reads permission.granted, and reading .granted of null would crash the app with “Cannot read properties of null”.
This screen lasts less than a second on a real phone.
Now explaining · lines 45–49React
Not allowed yet: explain why
When the phone answers, the hook gets a new value and React runs ScannerScreen again, from the top. Now permission is an object, so the first if is skipped.
permission.granted is true only when the user allowed the camera, so !permission.granted is true when the camera is not allowed yet. Then this return draws a title and one sentence that says why the app needs the camera. Users say yes more often when they know why — and both app stores ask apps to explain.
The phone answered: not allowed yet. React ran the component again.
Now explaining · lines 50–51expo-camera
“Allow camera” calls requestPermission
permission.canAskAgain says if the phone will still show its dialog. condition ? A : B picks A when the condition is true and B when it is false. Inside JSX it is wrapped in { }.
The button gets onPress={requestPermission} — the name of the function, without (). We hand the button the function itself, and the button calls it later, when it is pressed. With () the function would run at once, while the screen is being drawn.
The user’s answer goes back into the hook, and React runs the component again.
Allow camera was pressed: the phone shows its own dialog.
Now explaining · lines 52–54React Native
Refused twice: “Open settings”
On Android, after Don’t allow two times, the phone stops showing the dialog: canAskAgain becomes false, and ? : picks the part after : — the Open settings button.
Linking.openSettings() (from React Native) opens this app’s page in the phone’s Settings, the only place where the user can still allow the camera. Here the button gets () => Linking.openSettings(): an arrow function that calls openSettings when the button is pressed. We need the arrow because openSettings must be called *with* () — and onPress={Linking.openSettings()} would open Settings at once, while drawing.
After two Don’t allow, the phone never shows its dialog again.
Now explaining · line 53React Native
In Settings, the user turns the camera on
This is the page Open settings opens (on the lab phone, a stand-in for the real Settings app). When the user chooses Allow only while using the app and goes back, the hook gets a new answer — granted: true — and React runs the component again.
The lab phone’s stand-in for the phone’s Settings page.
Now explaining · lines 55–58React
“Back” and the end of the block
Back calls onBack, the function App.tsx gave this screen as a prop: the app goes back to the home screen. Then the block ends: </View> closes the screen, ); ends the return, and } ends the if.
Back returns to the home screen.
Now explaining · lines 60–66expo-camera
Allowed: the last return draws the camera
granted is true now, so both ifs are skipped. There is no result yet (that comes in Step B), so the last return runs: the camera, with the scan frame and the buttons on top.
The order of the ifs is the order of the questions: first “no answer yet?”, then “not allowed?”, and only then the camera. If the camera came first, it would open without permission — the error you saw at the start.
The camera is open. The Console shows the answer.
- line 3 Where the hook comes from
This line is already in the file. It takes three names from the
expo-camerapackage: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 wordtypein front says it is used only by TypeScript, never when the app runs.
- line 16 Read the permission (you write this)
The first line you write, at the top of the component.
useCameraPermissions()gives back two things in an array. The square brackets on the left take them out and give each one a name:permission— what the phone has answered so far.requestPermission— a function. Calling it makes the phone show its permission dialog.
You choose the two names, but the order is fixed: first the answer, then the function. At the very start
permissionisnull— the hook is still asking the phone. - lines 37–43 No answer yet: show “Checking camera permission…”
!means not.!permissionistruewhenpermissionhas no value yet (null). Then thisreturngives a small screen with one text.Because
returnends the function, nothing below this block runs whilepermissionisnull. That matters: the next block readspermission.granted, and reading.grantedofnullwould crash the app with “Cannot read properties of null”. - lines 45–49 Not allowed yet: explain why
When the phone answers, the hook gets a new value and React runs
ScannerScreenagain, from the top. Nowpermissionis an object, so the firstifis skipped.permission.grantedistrueonly when the user allowed the camera, so!permission.grantedistruewhen the camera is not allowed yet. Then thisreturndraws a title and one sentence that says why the app needs the camera. Users say yes more often when they know why — and both app stores ask apps to explain. - lines 50–51 “Allow camera” calls
requestPermissionpermission.canAskAgainsays if the phone will still show its dialog.condition ? A : Bpicks A when the condition is true and B when it is false. Inside JSX it is wrapped in{ }.The button gets
onPress={requestPermission}— the name of the function, without(). We hand the button the function itself, and the button calls it later, when it is pressed. With()the function would run at once, while the screen is being drawn.The user’s answer goes back into the hook, and React runs the component again.
- lines 52–54 Refused twice: “Open settings”
On Android, after Don’t allow two times, the phone stops showing the dialog:
canAskAgainbecomesfalse, and? :picks the part after:— the Open settings button.Linking.openSettings()(from React Native) opens this app’s page in the phone’s Settings, the only place where the user can still allow the camera. Here the button gets() => Linking.openSettings(): an arrow function that callsopenSettingswhen the button is pressed. We need the arrow becauseopenSettingsmust be called *with*()— andonPress={Linking.openSettings()}would open Settings at once, while drawing. - line 53 In Settings, the user turns the camera on
This is the page Open settings opens (on the lab phone, a stand-in for the real Settings app). When the user chooses Allow only while using the app and goes back, the hook gets a new answer —
granted: true— and React runs the component again. - lines 55–58 “Back” and the end of the block
Back calls
onBack, the functionApp.tsxgave this screen as a prop: the app goes back to the home screen. Then the block ends:</View>closes the screen,);ends thereturn, and}ends theif. - lines 60–66 Allowed: the last
returndraws the cameragrantedistruenow, so bothifs are skipped. There is noresultyet (that comes in Step B), so the lastreturnruns: the camera, with the scan frame and the buttons on top.The order of the
ifs is the order of the questions: first “no answer yet?”, then “not allowed?”, and only then the camera. If the camera came first, it would open without permission — the error you saw at the start.
④ Your turn · Exercise 5
In the exercise, ScannerScreen.tsx has three TODO Step A comments. They mark where the + lines go:
- Line 16: replace this comment with the hook line
const [permission, requestPermission] = useCameraPermissions(); - Lines 37–38: replace these two comments with the two
ifblocks: “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.
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.
- The camera is open. The finger presses QR: Website: that code is now “in front of the camera”.
- The result card opens: a green check, WEBSITE, and the text inside the code,
https://expo.dev. - The Console shows one line,
Scanned: https://expo.dev— one code, one result.
Each kind of code gives its own card:
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:
- The camera must look for QR codes, and send each one it reads to your function — two props of
CameraView. - 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 ✓- 1 / 7The camera reads every frame
A camera takes many pictures (frames) every second. While a QR code is in front of it,
onBarcodeScannedruns for every frame that shows the code — here 5 reads in less than one second. Each read callshandleScan. - 2 / 7Without a lock: 5 results
With no lock, every call runs to the end: 5 Scanned: lines in the Console, the result set 5 times, 5 vibrations. The user held up one code.
- 3 / 7The lock: a ref that starts open
useRef(false)makes a box that keeps a value while the screen draws again and again. You read and change it with.current.locked.currentisfalse: the lock is open. - 4 / 7Read 1 passes and closes the lock
if (locked.current) return;→false, so the function goes on.locked.current = true;closes the lock at once. Then the code is written to the Console and turned into the result. - 5 / 7Reads 2–5 stop at the first line
Now
locked.currentistrue, soreturnendshandleScanon its first line. Nothing else runs: still one Scanned: line, one result, one vibration. - 6 / 7Why a ref and not a state?
A state changes only when React draws the screen again — and reads 2 and 3 can arrive before that, still seeing the old
false. A ref changes at once: read 2 already seestrue. A ref also does not draw the screen again. - 7 / 7Scan again opens the lock
Scan again calls
scanAgain:locked.current = falseopens the lock, andsetResult(null)removes the result, so the camera comes back — ready for the next code.
Try it yourself: switch the lock off and on, press a code, and count the lines in the Console.
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:
1 // The kinds of QR content the app understands. 2 export type ScanKind = 'website' | 'wifi' | 'email' | 'phone' | 'text'; 3 4 // A good scan has a kind, a label and the text. A bad scan has an error message. 5 export type ScanResult = 6 | { ok: true; kind: ScanKind; label: string; value: string } 7 | { ok: false; error: string }; 8 9 const MAX_LENGTH = 500; 10 11 export function parseScan(data: string | null | undefined): ScanResult { 12 const value = (data ?? '').trim(); 13 const lower = value.toLowerCase(); 14 15 if (value === '') { 16 return { ok: false, error: 'This QR code is empty.' }; 17 } 18 if (value.length > MAX_LENGTH) { 19 return { ok: false, error: 'This QR code is too long to show.' }; 20 } 21 if (lower.startsWith('https://') || lower.startsWith('http://')) { 22 return { ok: true, kind: 'website', label: 'Website', value }; 23 } 24 if (lower.startsWith('wifi:')) { 25 return { ok: true, kind: 'wifi', label: 'Wi-Fi network', value }; 26 } 27 if (lower.startsWith('mailto:')) { 28 return { ok: true, kind: 'email', label: 'Email', value }; 29 } 30 if (lower.startsWith('tel:')) { 31 return { ok: true, kind: 'phone', label: 'Phone number', value }; 32 } 33 return { ok: true, kind: 'text', label: 'Text', value }; 34 }
On the lab phone now




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.
Now explaining · lines 5–7
A good scan or a bad scan
ScanResult is one of two shapes:
- a good scan:
ok: true, with akind, alabel(the title on the card) and thevalue(the text); - a bad scan:
ok: false, with anerrormessage.
Checking result.ok tells TypeScript which shape it has, so it lets you read kind only on a good scan.
Now explaining · lines 11–13
Clean the text first
parseScan accepts a string, null or undefined: it must never crash, whatever the camera gives. data ?? '' turns null or undefined into an empty text, and .trim() removes the spaces at both ends. lower is a lowercase copy, so HTTPS:// and https:// are treated the same.
Now explaining · lines 15–20
The two bad cases
An empty code, and a code longer than 500 characters (MAX_LENGTH, line 9). Each return ends the function at once, with ok: false and the message the card shows.
QR: Empty code (three spaces) → ok: false.
Now explaining · lines 21–23
A website
startsWith checks how the text begins. https:// or http:// → a website. || means or: one of the two is enough.
QR: Website → kind website. Only websites get Open link.
Now explaining · lines 24–26
A Wi-Fi network
A Wi-Fi QR code starts with WIFI:. This branch returns the whole text as the value — so the card shows the password too. You fix it in Part 10.
QR: Wi-Fi → the whole code, with the password. Part 10 fixes this.
Now explaining · lines 27–32
An email or a phone number
mailto: → an email address; tel: → a phone number. These two are the standard beginnings for QR codes that open the mail app or the phone app.
Now explaining · line 33
Anything else is text
When no if matched, the code is plain text, like Room 3.12. This is the last line, so parseScan always returns a result.
QR: Text → kind text.
- line 2 Five kinds of content
ScanKindlists 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. - lines 5–7 A good scan or a bad scan
ScanResultis one of two shapes:- a good scan:
ok: true, with akind, alabel(the title on the card) and thevalue(the text); - a bad scan:
ok: false, with anerrormessage.
Checking
result.oktells TypeScript which shape it has, so it lets you readkindonly on a good scan. - a good scan:
- lines 11–13 Clean the text first
parseScanaccepts a string,nullorundefined: it must never crash, whatever the camera gives.data ?? ''turnsnullorundefinedinto an empty text, and.trim()removes the spaces at both ends.loweris a lowercase copy, soHTTPS://andhttps://are treated the same. - lines 15–20 The two bad cases
An empty code, and a code longer than 500 characters (
MAX_LENGTH, line 9). Eachreturnends the function at once, withok: falseand the message the card shows. - lines 21–23 A website
startsWithchecks how the text begins.https://orhttp://→ a website.||means or: one of the two is enough. - lines 24–26 A Wi-Fi network
A Wi-Fi QR code starts with
WIFI:. This branch returns the whole text as the value — so the card shows the password too. You fix it in Part 10. - lines 27–32 An email or a phone number
mailto:→ an email address;tel:→ a phone number. These two are the standard beginnings for QR codes that open the mail app or the phone app. - line 33 Anything else is text
When no
ifmatched, the code is plain text, likeRoom 3.12. This is the last line, soparseScanalways returns a result.
On top of the camera the scanner draws the blue frame with the moving line — another finished file:
1 import { useEffect, useRef } from 'react'; 2 import { Animated, StyleSheet, View } from 'react-native'; 3 4 const SIZE = 250; 5 6 export default function ScanFrame() { 7 const position = useRef(new Animated.Value(0)).current; 8 9 useEffect(() => { 10 const loop = Animated.loop( 11 Animated.sequence([ 12 Animated.timing(position, { toValue: 1, duration: 1500, useNativeDriver: true }), 13 Animated.timing(position, { toValue: 0, duration: 1500, useNativeDriver: true }), 14 ]), 15 ); 16 loop.start(); 17 return () => loop.stop(); 18 }, [position]); 19 20 const translateY = position.interpolate({ inputRange: [0, 1], outputRange: [0, SIZE - 4] }); 21 22 return ( 23 <View style={styles.overlay}> 24 <View style={styles.frame}> 25 <View style={[styles.corner, styles.topLeft]} /> 26 <View style={[styles.corner, styles.topRight]} /> 27 <View style={[styles.corner, styles.bottomLeft]} /> 28 <View style={[styles.corner, styles.bottomRight]} /> 29 <Animated.View style={[styles.line, { transform: [{ translateY }] }]} /> 30 </View> 31 </View> 32 ); 33 } 34 35 const styles = StyleSheet.create({ 36 overlay: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }, 37 frame: { width: SIZE, height: SIZE }, 38 corner: { position: 'absolute', width: 44, height: 44, borderColor: '#38BDF8' }, 39 topLeft: { top: 0, left: 0, borderTopWidth: 5, borderLeftWidth: 5, borderTopLeftRadius: 18 }, 40 topRight: { top: 0, right: 0, borderTopWidth: 5, borderRightWidth: 5, borderTopRightRadius: 18 }, 41 bottomLeft: { bottom: 0, left: 0, borderBottomWidth: 5, borderLeftWidth: 5, borderBottomLeftRadius: 18 }, 42 bottomRight: { bottom: 0, right: 0, borderBottomWidth: 5, borderRightWidth: 5, borderBottomRightRadius: 18 }, 43 line: { position: 'absolute', left: 12, right: 12, height: 4, borderRadius: 2, backgroundColor: '#38BDF8' }, 44 });
On the lab phone now

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.
Now explaining · line 7React Native
A number for the animation
Animated.Value is a number that an animation changes without drawing the component again. useRef(…).current keeps the same number for the whole life of the screen.
Now explaining · lines 9–15React Native
A loop of two moves
Animated.loop repeats a sequence of two moves for ever: from 0 to 1 in 1.5 seconds (down), then back to 0 (up). useNativeDriver: true lets the phone run the animation by itself, without JavaScript.
Now explaining · lines 16–17React
Start, and stop when the screen closes
loop.start() runs when the frame appears. The function that useEffect returns runs when the frame disappears (the cleanup): loop.stop(). Without it the animation would keep running after the camera closed.
Now explaining · line 20React Native
From 0…1 to points
interpolate turns the number 0…1 into 0…246 points: how far down the line is.
Now explaining · lines 23–31React Native
Four corners and the line
Four corner pieces, and the line that moves with transform: [{ translateY }].
Now explaining · line 36React Native
Touches go through
The frame covers the whole screen (position: 'absolute' with all four sides at 0). pointerEvents: 'none' lets every touch go through it to the buttons and codes below.
- line 4 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.)
- line 7 A number for the animation
Animated.Valueis a number that an animation changes without drawing the component again.useRef(…).currentkeeps the same number for the whole life of the screen. - lines 9–15 A loop of two moves
Animated.looprepeats asequenceof two moves for ever: from 0 to 1 in 1.5 seconds (down), then back to 0 (up).useNativeDriver: truelets the phone run the animation by itself, without JavaScript. - lines 16–17 Start, and stop when the screen closes
loop.start()runs when the frame appears. The function thatuseEffectreturns runs when the frame disappears (the cleanup):loop.stop(). Without it the animation would keep running after the camera closed. - line 20 From 0…1 to points
interpolateturns the number 0…1 into 0…246 points: how far down the line is. - lines 23–31 Four corners and the line
Four corner pieces, and the line that moves with
transform: [{ translateY }]. - line 36 Touches go through
The frame covers the whole screen (
position: 'absolute'with all four sides at 0).pointerEvents: 'none'lets every touch go through it to the buttons and codes below.
③ The code, line by line
ScannerScreen.tsx after Step B. Six new lines (+): two props for the camera and four for the lock.
1 import { useRef, useState } from 'react'; 2 import { Linking, StyleSheet, Text, View } from 'react-native'; 3 import { CameraView, useCameraPermissions, type CameraType } from 'expo-camera'; 4 import { parseScan, type ScanResult } from '../scan/parseScan'; 5 import { tapFeedback } from '../scan/feedback'; 6 import AppButton from '../components/AppButton'; 7 import ResultCard from '../components/ResultCard'; 8 import ScanFrame from '../components/ScanFrame'; 9 10 // The fixed code the "Use sample QR" button sends, for tests (no real camera needed) 11 export const SAMPLE_QR = 'https://expo.dev'; 12 13 type Props = { onBack: () => void }; 14 15 export default function ScannerScreen({ onBack }: Props) { 16 const [permission, requestPermission] = useCameraPermissions(); 17 const [facing, setFacing] = useState<CameraType>('back'); 18 const [result, setResult] = useState<ScanResult | null>(null); 19 const [cameraError, setCameraError] = useState<string | null>(null); 20+ const locked = useRef(false); 21 22 function handleScan(data: string) { 23+ if (locked.current) return; 24+ locked.current = true; 25 console.log('Scanned:', data); 26 setResult(parseScan(data)); 27 } 28 29 function scanAgain() { 30+ locked.current = false; 31 setResult(null); 32 } 33 34 function flipCamera() { 35 // TODO Step D: a small tap (tapFeedback), then switch between 'back' and 'front' 36 } 37 38 if (!permission) { 39 return ( 40 <View style={styles.center}> 41 <Text style={styles.text}>Checking camera permission…</Text> 42 </View> 43 ); 44 } 45 46 if (!permission.granted) { 47 return ( 48 <View style={styles.center}> 49 <Text style={styles.title}>Camera permission needed</Text> 50 <Text style={styles.text}>Smart QR uses the camera only to read QR codes.</Text> 51 {permission.canAskAgain ? ( 52 <AppButton title="Allow camera" testID="allow-camera" onPress={requestPermission} /> 53 ) : ( 54 <AppButton title="Open settings" testID="open-settings" onPress={() => Linking.openSettings()} /> 55 )} 56 <AppButton title="Back" variant="light" onPress={onBack} /> 57 </View> 58 ); 59 } 60 61 if (result) { 62 return <ResultCard result={result} onScanAgain={scanAgain} />; 63 } 64 65 return ( 66 <View style={styles.screen}> 67 <CameraView 68 style={styles.camera} 69 facing={facing} 70+ barcodeScannerSettings={{ barcodeTypes: ['qr'] }} 71+ onBarcodeScanned={(scan) => handleScan(scan.data)} 72 onMountError={(error) => setCameraError(error.message)} 73 /> 74 <ScanFrame /> 75 <Text style={styles.hint}>Point the camera at a QR code</Text> 76 {cameraError && <Text style={styles.error}>Camera error: {cameraError}</Text>} 77 <View style={styles.controls}> 78 <AppButton title="Back" variant="light" onPress={onBack} /> 79 <AppButton title="Flip camera" variant="light" testID="flip-camera" onPress={flipCamera} /> 80 {__DEV__ && <AppButton title="Use sample QR" variant="light" testID="sample-scan" onPress={() => handleScan(SAMPLE_QR)} />} 81 </View> 82 </View> 83 ); 84 } 85 86 const styles = StyleSheet.create({ 87 screen: { flex: 1, backgroundColor: '#000000' }, 88 camera: { flex: 1 }, 89 center: { flex: 1, backgroundColor: '#0F172A', alignItems: 'center', justifyContent: 'center', padding: 32, gap: 16 }, 90 title: { color: '#FFFFFF', fontSize: 24, fontWeight: '800', textAlign: 'center' }, 91 text: { color: '#CBD5E1', fontSize: 16, textAlign: 'center' }, 92 hint: { position: 'absolute', top: 72, alignSelf: 'center', color: '#FFFFFF', fontSize: 16, fontWeight: '600' }, 93 error: { position: 'absolute', top: 110, left: 24, right: 24, color: '#FCA5A5', textAlign: 'center' }, 94 controls: { position: 'absolute', bottom: 40, left: 16, right: 16, flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', gap: 10 }, 95 });
On the lab phone now


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.
Now explaining · line 71expo-camera
Send each code to handleScan (you write this)
onBarcodeScanned is a function the camera calls each time it reads a code. The camera gives it one object, here named scan:
scan.data— the text inside the code, e.g.https://expo.dev;scan.type— the kind of code,'qr'.
(scan) => handleScan(scan.data) is an arrow function: it takes the object and passes only the text to handleScan.
Now explaining · line 20React
The lock (you write this)
useRef(false) makes a box that keeps one value while React draws the screen again and again. You read and change the value with .current.
locked.current starts as false: the lock is open. Why not useState? A state changes only when React draws the screen again — the camera’s next read can come before that. A ref changes at once, and changing it does not draw the screen again.
Now explaining · line 23React
Closed? Stop here (you write this)
if (locked.current) return; — when the lock is already closed, return ends handleScan on its first line. Nothing else runs: no log, no new result, no vibration.
Now explaining · line 24React
Open? Close it now (you write this)
The first read finds the lock open, goes past line 23, and closes it at once: locked.current = true;. Every read after this one stops at line 23.
Now explaining · lines 25–26React
Log it, and make the result
These two lines were already there. console.log writes the code’s text to the Console — one line per call, so you can count the calls.
setResult(parseScan(data)) turns the text into a result and keeps it in the result state. A new state makes React run ScannerScreen again.
One code → one Scanned: line, one result card.
Now explaining · lines 61–63React
A result replaces the camera
if (result) is now true, so this return draws the ResultCard instead of the camera. The camera is not drawn any more, so it closes.
Now explaining · lines 29–31React
Scan again: open the lock (you write line 30)
Scan again on the card calls scanAgain. locked.current = false; opens the lock, and setResult(null) removes the result, so the last return draws the camera again — ready for the next code.
Scan again → the camera is back, ready for the next code.
- line 70 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, …). - line 71 Send each code to handleScan (you write this)
onBarcodeScannedis a function the camera calls each time it reads a code. The camera gives it one object, here namedscan:scan.data— the text inside the code, e.g.https://expo.dev;scan.type— the kind of code,'qr'.
(scan) => handleScan(scan.data)is an arrow function: it takes the object and passes only the text tohandleScan. - line 20 The lock (you write this)
useRef(false)makes a box that keeps one value while React draws the screen again and again. You read and change the value with.current.locked.currentstarts asfalse: the lock is open. Why notuseState? A state changes only when React draws the screen again — the camera’s next read can come before that. A ref changes at once, and changing it does not draw the screen again. - line 23 Closed? Stop here (you write this)
if (locked.current) return;— when the lock is already closed,returnendshandleScanon its first line. Nothing else runs: no log, no new result, no vibration. - line 24 Open? Close it now (you write this)
The first read finds the lock open, goes past line 23, and closes it at once:
locked.current = true;. Every read after this one stops at line 23. - lines 25–26 Log it, and make the result
These two lines were already there.
console.logwrites the code’s text to the Console — one line per call, so you can count the calls.setResult(parseScan(data))turns the text into a result and keeps it in theresultstate. A new state makes React runScannerScreenagain. - lines 61–63 A result replaces the camera
if (result)is now true, so thisreturndraws the ResultCard instead of the camera. The camera is not drawn any more, so it closes. - lines 29–31 Scan again: open the lock (you write line 30)
Scan again on the card calls
scanAgain.locked.current = false;opens the lock, andsetResult(null)removes the result, so the lastreturndraws the camera again — ready for the next code.
④ Your turn · Exercise 6
The four TODO Step B comments in the exercise:
- Line 20: the lock —
const locked = useRef(false); - Line 23:
if (locked.current) return;thenlocked.current = true; - Line 29:
locked.current = false; - Line 69: the two camera props,
barcodeScannerSettingsandonBarcodeScanned
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.
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.
- QR: Website — the result card opens and the phone shakes:
Haptics: notification success. - Scan again, then QR: Empty code — the error card opens.
- A different pattern plays:
Haptics: notification 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-hapticsplays 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.notificationAsyncgives back a Promise — a value that is ready a little later.awaitwaits for it, andawaitcan only be used inside anasyncfunction.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 }}
- 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.)
- 2 / 6A code is read
handleScanruns and callssetResult(parseScan(data)): the result is now in the state. - 3 / 6The card replaces the camera
A new state makes React run
ScannerScreenagain.if (result)now returns the ResultCard, so the camera is not drawn any more: the camera closes. - 4 / 6ResultCard’s
useEffectrunsuseEffectruns after the card is on the screen.result.okistrue, so it callssuccessFeedback()(a bad code would callerrorFeedback()). - 5 / 6
await: ask the phone and waitsuccessFeedbackis anasyncfunction.await Haptics.notificationAsync(…Success)asks the phone for the success pattern and waits until the phone has started it. The camera is closed, so every phone vibrates — iPhones too. - 6 / 6No motor?
catchitSome phones and tablets have no vibration motor: then the call throws an error.
catchcatches it and does nothing, so the app goes on — the card still shows. Withouttry / catchthe error would break the screen.
③ 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.
1 import * as Haptics from 'expo-haptics'; 2 3 // The phone's "success" vibration: the scan worked. 4+export async function successFeedback() { 5+ try { 6+ await Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success); 7+ } catch { 8+ // A phone with no vibration motor: the app still works without it. 9+ } 10+} 11 12 // The phone's "error" vibration: the app cannot use this code. 13+export async function errorFeedback() { 14+ try { 15+ await Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error); 16+ } catch { 17+ // No vibration motor: nothing to do. 18+ } 19+} 20 21 // A small tap for a button press, like flipping the camera. 22 export async function tapFeedback() { 23 try { 24 await Haptics.selectionAsync(); 25 } catch { 26 // No vibration motor: nothing to do. 27 } 28 }
On the lab phone now



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.
Now explaining · lines 22–28expo-haptics
Your model: the finished tapFeedback
Read the finished function first — the two you write have the same shape:
export async function— other files can import it (export), and it can useawait(async);try { await … }— ask the phone for the vibration and wait until it has started;catch { … }— a phone without a motor throws an error; we do nothing, and the app goes on.
Now explaining · lines 4–6expo-haptics
The success vibration (you write this)
Haptics.notificationAsync(…) plays one of three patterns: Success, Warning or Error. The pattern is a value of Haptics.NotificationFeedbackType. await waits until the phone has started it.
A good code: the phone plays the success pattern.
Now explaining · lines 7–9expo-haptics
No motor? Catch the error (you write this)
If the phone has no vibration motor, notificationAsync throws an error. catch catches it. The comment says why the block is empty: nothing to do — the app works without vibration.
Now explaining · lines 13–18expo-haptics
The error vibration (you write this)
The same shape, with Haptics.NotificationFeedbackType.Error: a different pattern, so the user can feel that something went wrong without looking.
A bad code: the phone plays the error pattern.
- line 1 Everything from expo-haptics, in one name
import * as Hapticsputs everything the package exports into one object calledHaptics:Haptics.notificationAsync,Haptics.NotificationFeedbackType,Haptics.selectionAsync, … - lines 22–28 Your model: the finished tapFeedback
Read the finished function first — the two you write have the same shape:
export async function— other files can import it (export), and it can useawait(async);try { await … }— ask the phone for the vibration and wait until it has started;catch { … }— a phone without a motor throws an error; we do nothing, and the app goes on.
- lines 4–6 The success vibration (you write this)
Haptics.notificationAsync(…)plays one of three patterns:Success,WarningorError. The pattern is a value ofHaptics.NotificationFeedbackType.awaitwaits until the phone has started it. - lines 7–9 No motor? Catch the error (you write this)
If the phone has no vibration motor,
notificationAsyncthrows an error.catchcatches it. The comment says why the block is empty: nothing to do — the app works without vibration. - lines 13–18 The error vibration (you write this)
The same shape, with
Haptics.NotificationFeedbackType.Error: a different pattern, so the user can feel that something went wrong without looking.
Who calls these functions? ResultCard — a finished file — as soon as it appears:
1 import { useEffect, useRef } from 'react'; 2 import { Animated, Linking, StyleSheet, Text, View } from 'react-native'; 3 import type { ScanResult } from '../scan/parseScan'; 4 import { errorFeedback, successFeedback } from '../scan/feedback'; 5 import AppButton from './AppButton'; 6 7 type Props = { result: ScanResult; onScanAgain: () => void }; 8 9 export default function ResultCard({ result, onScanAgain }: Props) { 10 const appear = useRef(new Animated.Value(0)).current; 11 12 useEffect(() => { 13 // The camera is closed now, so the vibration also works on iPhone. 14 if (result.ok) { 15 successFeedback(); 16 } else { 17 errorFeedback(); 18 } 19 Animated.spring(appear, { toValue: 1, friction: 6, useNativeDriver: true }).start(); 20 }, [result, appear]); 21 22 const scale = appear.interpolate({ inputRange: [0, 1], outputRange: [0.8, 1] }); 23 24 return ( 25 <View style={styles.screen}> 26 <Animated.View style={[styles.card, { opacity: appear, transform: [{ scale }] }]}> 27 <View style={[styles.badge, result.ok ? styles.good : styles.bad]}> 28 <Text style={styles.badgeText}>{result.ok ? '✓' : '!'}</Text> 29 </View> 30 <Text style={styles.label}>{result.ok ? result.label : "Can't use this code"}</Text> 31 <Text style={styles.value} selectable> 32 {result.ok ? result.value : result.error} 33 </Text> 34 {result.ok && result.kind === 'website' && ( 35 <Text accessibilityRole="link" style={styles.link} onPress={() => Linking.openURL(result.value)} testID="open-link"> 36 Open link 37 </Text> 38 )} 39 <AppButton title="Scan again" testID="scan-again" onPress={onScanAgain} /> 40 </Animated.View> 41 </View> 42 ); 43 } 44 45 const styles = StyleSheet.create({ 46 screen: { flex: 1, backgroundColor: '#0F172A', alignItems: 'center', justifyContent: 'center', padding: 24 }, 47 card: { width: '100%', backgroundColor: '#FFFFFF', borderRadius: 24, padding: 24, gap: 14, alignItems: 'center' }, 48 badge: { width: 64, height: 64, borderRadius: 32, alignItems: 'center', justifyContent: 'center' }, 49 good: { backgroundColor: '#22C55E' }, 50 bad: { backgroundColor: '#EF4444' }, 51 badgeText: { color: '#FFFFFF', fontSize: 32, fontWeight: '800' }, 52 label: { fontSize: 14, fontWeight: '700', color: '#64748B', textTransform: 'uppercase', letterSpacing: 1 }, 53 value: { fontSize: 19, color: '#0F172A', textAlign: 'center' }, 54 link: { fontSize: 16, color: '#0284C7', fontWeight: '700', padding: 6 }, 55 });
On the lab phone now


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.
Now explaining · line 10React Native
A number for the pop-in
appear goes from 0 to 1 when the card opens. It drives two animations at once: the fade-in and the zoom.
Now explaining · lines 12–18React
Vibrate when the card appears
useEffect runs its function after the card is on the screen — when the camera is already closed, so iPhones vibrate too.
A good result (result.ok) plays the success vibration; a bad one plays the error vibration.
Now explaining · lines 19–20React Native
Pop in — and only for a new result
Animated.spring moves appear from 0 to 1 with a small bounce. The list [result, appear] at the end tells React: run this effect again only when result changes — one vibration per scan.
Now explaining · line 22React Native
80 % → 100 %
interpolate turns 0…1 into a size: 80 % at the start, 100 % at the end.
Now explaining · lines 27–29React Native
✓ or !
A green ✓ for a good scan, a red ! for a bad one. ? : picks the style and the sign.
A bad code: a red !.
Now explaining · lines 30–33React Native
The title and the text
The label (“Website”) and the value — or “Can’t use this code” and the error message. selectable lets the user select and copy the text.
Now explaining · lines 34–38React Native
Open link — only for websites
&& draws the link only when both sides are true: a good result and the kind is website. Linking.openURL asks the phone to open the address in its browser.
Open link appears only on a website card.
Now explaining · line 39React Native
Scan again
Scan again calls onScanAgain — the scanAgain function ScannerScreen gave the card (Step B).
- lines 3–5 What the card uses
The result’s type, the two vibrations you wrote in
feedback.ts, and the app’s button. - line 10 A number for the pop-in
appeargoes from 0 to 1 when the card opens. It drives two animations at once: the fade-in and the zoom. - lines 12–18 Vibrate when the card appears
useEffectruns its function after the card is on the screen — when the camera is already closed, so iPhones vibrate too.A good result (
result.ok) plays the success vibration; a bad one plays the error vibration. - lines 19–20 Pop in — and only for a new result
Animated.springmovesappearfrom 0 to 1 with a small bounce. The list[result, appear]at the end tells React: run this effect again only whenresultchanges — one vibration per scan. - line 22 80 % → 100 %
interpolateturns 0…1 into a size: 80 % at the start, 100 % at the end. - lines 27–29 ✓ or !
A green ✓ for a good scan, a red ! for a bad one.
? :picks the style and the sign. - lines 30–33 The title and the text
The label (“Website”) and the value — or “Can’t use this code” and the error message.
selectablelets the user select and copy the text. - lines 34–38 Open link — only for websites
&&draws the link only when both sides are true: a good result and the kind iswebsite.Linking.openURLasks the phone to open the address in its browser. - line 39 Scan again
Scan again calls
onScanAgain— thescanAgainfunctionScannerScreengave the card (Step B).
④ Your turn · Exercise 7
The two TODO Step C comments in feedback.ts:
- Fill
successFeedbackwith thetry / await / catchof the success pattern - Fill
errorFeedbackthe same way, withError
Scan QR: Website, then QR: Empty code: the phone shakes, and the Console names each pattern. Then press Check.
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.
- The camera is open on the back camera.
- The finger presses Flip camera: a small tap (
Haptics: selection), and the label says Front camera. - A second press goes back to the back camera, with another tap.
② 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'.
facingis a state — a value the screen remembers (Lab 02:useState). Changing it withsetFacingmakes React runScannerScreenagain, andCameraViewgets the new side.- The button does two things, in order: a small tap you can feel, then the switch.
- The switch uses a function.
setFacingcan 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
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} />
- 1 / 5
facingis a stateuseState<CameraType>('back')keeps which camera is on. It starts as'back'.<CameraView facing={facing} />reads it, so the phone shows the back camera. - 2 / 5Press Flip camera
The button’s
onPressisflipCamera(no(): React calls it when the button is pressed). Its first line,tapFeedback(), plays the small selection tap. - 3 / 5The function form of
setFacingsetFacinggets a function, not a value. React calls it with the current value ('back'), and the function gives back the other side:current === 'back' ? 'front' : 'back'→'front'. - 4 / 5React draws the screen again
The state changed, so React runs
ScannerScreenagain.facingis now'front',CameraViewgetsfacing='front', and the phone shows the front camera. - 5 / 5Press again: back to
'back'The same function turns
'front'into'back'. Because React always passes the newest value, two fast presses still end on the right side.
③ The code, line by line
The finished ScannerScreen.tsx. Step D adds two lines (+) inside flipCamera.
1 import { useRef, useState } from 'react'; 2 import { Linking, StyleSheet, Text, View } from 'react-native'; 3 import { CameraView, useCameraPermissions, type CameraType } from 'expo-camera'; 4 import { parseScan, type ScanResult } from '../scan/parseScan'; 5 import { tapFeedback } from '../scan/feedback'; 6 import AppButton from '../components/AppButton'; 7 import ResultCard from '../components/ResultCard'; 8 import ScanFrame from '../components/ScanFrame'; 9 10 // The fixed code the "Use sample QR" button sends, for tests (no real camera needed) 11 export const SAMPLE_QR = 'https://expo.dev'; 12 13 type Props = { onBack: () => void }; 14 15 export default function ScannerScreen({ onBack }: Props) { 16 const [permission, requestPermission] = useCameraPermissions(); 17 const [facing, setFacing] = useState<CameraType>('back'); 18 const [result, setResult] = useState<ScanResult | null>(null); 19 const [cameraError, setCameraError] = useState<string | null>(null); 20 const locked = useRef(false); 21 22 function handleScan(data: string) { 23 if (locked.current) return; 24 locked.current = true; 25 console.log('Scanned:', data); 26 setResult(parseScan(data)); 27 } 28 29 function scanAgain() { 30 locked.current = false; 31 setResult(null); 32 } 33 34 function flipCamera() { 35+ tapFeedback(); 36+ setFacing((current) => (current === 'back' ? 'front' : 'back')); 37 } 38 39 if (!permission) { 40 return ( 41 <View style={styles.center}> 42 <Text style={styles.text}>Checking camera permission…</Text> 43 </View> 44 ); 45 } 46 47 if (!permission.granted) { 48 return ( 49 <View style={styles.center}> 50 <Text style={styles.title}>Camera permission needed</Text> 51 <Text style={styles.text}>Smart QR uses the camera only to read QR codes.</Text> 52 {permission.canAskAgain ? ( 53 <AppButton title="Allow camera" testID="allow-camera" onPress={requestPermission} /> 54 ) : ( 55 <AppButton title="Open settings" testID="open-settings" onPress={() => Linking.openSettings()} /> 56 )} 57 <AppButton title="Back" variant="light" onPress={onBack} /> 58 </View> 59 ); 60 } 61 62 if (result) { 63 return <ResultCard result={result} onScanAgain={scanAgain} />; 64 } 65 66 return ( 67 <View style={styles.screen}> 68 <CameraView 69 style={styles.camera} 70 facing={facing} 71 barcodeScannerSettings={{ barcodeTypes: ['qr'] }} 72 onBarcodeScanned={(scan) => handleScan(scan.data)} 73 onMountError={(error) => setCameraError(error.message)} 74 /> 75 <ScanFrame /> 76 <Text style={styles.hint}>Point the camera at a QR code</Text> 77 {cameraError && <Text style={styles.error}>Camera error: {cameraError}</Text>} 78 <View style={styles.controls}> 79 <AppButton title="Back" variant="light" onPress={onBack} /> 80 <AppButton title="Flip camera" variant="light" testID="flip-camera" onPress={flipCamera} /> 81 {__DEV__ && <AppButton title="Use sample QR" variant="light" testID="sample-scan" onPress={() => handleScan(SAMPLE_QR)} />} 82 </View> 83 </View> 84 ); 85 } 86 87 const styles = StyleSheet.create({ 88 screen: { flex: 1, backgroundColor: '#000000' }, 89 camera: { flex: 1 }, 90 center: { flex: 1, backgroundColor: '#0F172A', alignItems: 'center', justifyContent: 'center', padding: 32, gap: 16 }, 91 title: { color: '#FFFFFF', fontSize: 24, fontWeight: '800', textAlign: 'center' }, 92 text: { color: '#CBD5E1', fontSize: 16, textAlign: 'center' }, 93 hint: { position: 'absolute', top: 72, alignSelf: 'center', color: '#FFFFFF', fontSize: 16, fontWeight: '600' }, 94 error: { position: 'absolute', top: 110, left: 24, right: 24, color: '#FCA5A5', textAlign: 'center' }, 95 controls: { position: 'absolute', bottom: 40, left: 16, right: 16, flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', gap: 10 }, 96 });
On the lab phone now


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.
Now explaining · line 70expo-camera
The camera reads it
facing={facing} gives the state to CameraView. When the state changes, React draws the screen again and the camera switches sides.
Now explaining · line 80React
The button
onPress={flipCamera} — the name of the function, without (): the button calls it when it is pressed (the same rule as in Step A).
Now explaining · line 35expo-haptics
A small tap first (you write this)
tapFeedback() is the finished function from feedback.ts: the lightest vibration, the one phones play when a choice changes.
The finger presses Flip camera: a small tap.
Now explaining · line 36React
Switch sides (you write this)
setFacing gets a function instead of a value. React calls it with the current value, and the function returns the new one: current === 'back' ? 'front' : 'back'.
Why a function? Because React always passes the newest value. With setFacing(facing === 'back' ? 'front' : 'back'), two quick presses could both read the old facing and leave the camera on the same side.
The front camera.
- line 17 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'. - line 70 The camera reads it
facing={facing}gives the state toCameraView. When the state changes, React draws the screen again and the camera switches sides. - line 80 The button
onPress={flipCamera}— the name of the function, without(): the button calls it when it is pressed (the same rule as in Step A). - line 35 A small tap first (you write this)
tapFeedback()is the finished function fromfeedback.ts: the lightest vibration, the one phones play when a choice changes. - line 36 Switch sides (you write this)
setFacinggets a function instead of a value. React calls it with the current value, and the function returns the new one:current === 'back' ? 'front' : 'back'.Why a function? Because React always passes the newest value. With
setFacing(facing === 'back' ? 'front' : 'back'), two quick presses could both read the oldfacingand leave the camera on the same side.
④ Your turn · Exercise 8
The last TODO of the scanner, inside flipCamera:
- Line 35:
tapFeedback();thensetFacing((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.
The finished scanner
All four steps together. The whole file, one part at a time:
1 import { useRef, useState } from 'react'; 2 import { Linking, StyleSheet, Text, View } from 'react-native'; 3 import { CameraView, useCameraPermissions, type CameraType } from 'expo-camera'; 4 import { parseScan, type ScanResult } from '../scan/parseScan'; 5 import { tapFeedback } from '../scan/feedback'; 6 import AppButton from '../components/AppButton'; 7 import ResultCard from '../components/ResultCard'; 8 import ScanFrame from '../components/ScanFrame'; 9 10 // The fixed code the "Use sample QR" button sends, for tests (no real camera needed) 11 export const SAMPLE_QR = 'https://expo.dev'; 12 13 type Props = { onBack: () => void }; 14 15 export default function ScannerScreen({ onBack }: Props) { 16 const [permission, requestPermission] = useCameraPermissions(); 17 const [facing, setFacing] = useState<CameraType>('back'); 18 const [result, setResult] = useState<ScanResult | null>(null); 19 const [cameraError, setCameraError] = useState<string | null>(null); 20 const locked = useRef(false); 21 22 function handleScan(data: string) { 23 if (locked.current) return; 24 locked.current = true; 25 console.log('Scanned:', data); 26 setResult(parseScan(data)); 27 } 28 29 function scanAgain() { 30 locked.current = false; 31 setResult(null); 32 } 33 34 function flipCamera() { 35 tapFeedback(); 36 setFacing((current) => (current === 'back' ? 'front' : 'back')); 37 } 38 39 if (!permission) { 40 return ( 41 <View style={styles.center}> 42 <Text style={styles.text}>Checking camera permission…</Text> 43 </View> 44 ); 45 } 46 47 if (!permission.granted) { 48 return ( 49 <View style={styles.center}> 50 <Text style={styles.title}>Camera permission needed</Text> 51 <Text style={styles.text}>Smart QR uses the camera only to read QR codes.</Text> 52 {permission.canAskAgain ? ( 53 <AppButton title="Allow camera" testID="allow-camera" onPress={requestPermission} /> 54 ) : ( 55 <AppButton title="Open settings" testID="open-settings" onPress={() => Linking.openSettings()} /> 56 )} 57 <AppButton title="Back" variant="light" onPress={onBack} /> 58 </View> 59 ); 60 } 61 62 if (result) { 63 return <ResultCard result={result} onScanAgain={scanAgain} />; 64 } 65 66 return ( 67 <View style={styles.screen}> 68 <CameraView 69 style={styles.camera} 70 facing={facing} 71 barcodeScannerSettings={{ barcodeTypes: ['qr'] }} 72 onBarcodeScanned={(scan) => handleScan(scan.data)} 73 onMountError={(error) => setCameraError(error.message)} 74 /> 75 <ScanFrame /> 76 <Text style={styles.hint}>Point the camera at a QR code</Text> 77 {cameraError && <Text style={styles.error}>Camera error: {cameraError}</Text>} 78 <View style={styles.controls}> 79 <AppButton title="Back" variant="light" onPress={onBack} /> 80 <AppButton title="Flip camera" variant="light" testID="flip-camera" onPress={flipCamera} /> 81 {__DEV__ && <AppButton title="Use sample QR" variant="light" testID="sample-scan" onPress={() => handleScan(SAMPLE_QR)} />} 82 </View> 83 </View> 84 ); 85 } 86 87 const styles = StyleSheet.create({ 88 screen: { flex: 1, backgroundColor: '#000000' }, 89 camera: { flex: 1 }, 90 center: { flex: 1, backgroundColor: '#0F172A', alignItems: 'center', justifyContent: 'center', padding: 32, gap: 16 }, 91 title: { color: '#FFFFFF', fontSize: 24, fontWeight: '800', textAlign: 'center' }, 92 text: { color: '#CBD5E1', fontSize: 16, textAlign: 'center' }, 93 hint: { position: 'absolute', top: 72, alignSelf: 'center', color: '#FFFFFF', fontSize: 16, fontWeight: '600' }, 94 error: { position: 'absolute', top: 110, left: 24, right: 24, color: '#FCA5A5', textAlign: 'center' }, 95 controls: { position: 'absolute', bottom: 40, left: 16, right: 16, flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', gap: 10 }, 96 });
On the lab phone now






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.
Now explaining · lines 10–11React
The sample code
The text the Use sample QR button sends. Tests use it too, because a test has no QR code to point at.
Now explaining · line 16expo-camera
Step A: the permission
The permission, and the function that asks for it.
Now explaining · lines 17–19React
Three states
Which camera is on, the result of the last scan (null while scanning), and a camera error message.
Now explaining · line 20React
Step B: the lock
A ref: it changes at once and does not draw the screen again.
Now explaining · lines 22–27React
handleScan
Stop if the lock is closed; otherwise close it, write the code to the Console, and turn the text into a result. Setting result shows the ResultCard.
Now explaining · lines 29–32React
scanAgain
Open the lock, then clear the result. The camera comes back.
Now explaining · lines 34–37React
Step D: flipCamera
A small tap, then switch facing. The function form always gets the newest value.
Now explaining · lines 39–45React
State 1 — no answer yet
permission is null: the hook is still asking the phone.
Now explaining · lines 47–60expo-camera
State 2 — not allowed
Explain why, then Allow camera (calls requestPermission), or Open settings when canAskAgain is false. Back returns home.
Now explaining · lines 62–64React
A scan happened
Show the result card instead of the camera. This closes the camera.
Now explaining · lines 68–74expo-camera
State 3 — the camera
Which side, QR codes only, each read goes to handleScan, and errors are kept in cameraError.
Now explaining · lines 75–77React Native
On top of the camera
The scan frame, a hint, and the error message if there is one (&& shows it only when it is not null).
Now explaining · lines 78–82React Native
The buttons
__DEV__ is true while you develop (Expo Go) and false in a store build: Use sample QR exists only while you develop.
- lines 1–8 Imports
React’s hooks, React Native’s parts, the camera (
CameraView,useCameraPermissionsand theCameraTypetype), the parser, the tap vibration, and the three components. - lines 10–11 The sample code
The text the Use sample QR button sends. Tests use it too, because a test has no QR code to point at.
- line 16 Step A: the permission
The permission, and the function that asks for it.
- lines 17–19 Three states
Which camera is on, the result of the last scan (
nullwhile scanning), and a camera error message. - line 20 Step B: the lock
A ref: it changes at once and does not draw the screen again.
- lines 22–27 handleScan
Stop if the lock is closed; otherwise close it, write the code to the Console, and turn the text into a result. Setting
resultshows the ResultCard. - lines 29–32 scanAgain
Open the lock, then clear the result. The camera comes back.
- lines 34–37 Step D: flipCamera
A small tap, then switch
facing. The function form always gets the newest value. - lines 39–45 State 1 — no answer yet
permissionisnull: the hook is still asking the phone. - lines 47–60 State 2 — not allowed
Explain why, then Allow camera (calls
requestPermission), or Open settings whencanAskAgainis false. Back returns home. - lines 62–64 A scan happened
Show the result card instead of the camera. This closes the camera.
- lines 68–74 State 3 — the camera
Which side, QR codes only, each read goes to
handleScan, and errors are kept incameraError. - lines 75–77 On top of the camera
The scan frame, a hint, and the error message if there is one (
&&shows it only when it is notnull). - lines 78–82 The buttons
__DEV__is true while you develop (Expo Go) and false in a store build: Use sample QR exists only while you develop.
The same scanner on a real Android phone (an emulator, in Expo Go):
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.
- The terminal panel shows the command it runs:
npm test -- __tests__/parseScan-test.ts. - The finger presses ▶ Run tests.
- 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' });});
{ ok: true, kind: 'website''text', … }{ ok: true, kind: 'website', … }- 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. - 2 / 5Run one test: call your code
Each
test(…)is run on its own. Inside it, the test calls your code like any other file would:parseScan('https://expo.dev')gives back an object. - 3 / 5Compare: received = expected? → ✓
expect(result).toEqual({ … })compares two values: what your code gave (received) and what the test says it must be (expected). Every field is the same, so the test passes: ✓. - 4 / 5A different value → ✕
If your code gave something else — here a different
kind— the values differ and the test fails: ✕. Jest shows both values, the line of the test, and goes on with the next test. - 5 / 5The summary
After the last test Jest prints a summary: how many test files and tests passed or failed, and the time. One failed test means something that worked before is broken — a regression.
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
- The real app in Expo Go on the emulator (or a phone). Real taps, the real permission dialog, the real screens.
- What is fake
- Nothing is fake. Only the QR code: the flow presses “Use sample QR” (a development-only button).
- Speed
- Slowest: about a minute (Expo Go opens the project first).
- Catches
- The parts do not work together: the app does not start, a screen never appears, a button leads nowhere.
- In Smart QR
.maestro/scan-sample.yaml- Run it
maestro test .maestro/scan-sample.yaml -e APP_URL=exp://127.0.0.1:8081
- What really runs
- One screen (ScannerScreen), drawn in Node on your computer. The test presses its buttons and reads its text.
- What is fake
- The camera (a fake CameraView with “scan” buttons) and the vibration motor (jest.mock).
- Speed
- Fast: a second or two.
- Catches
- The wrong screen for a state, a button that calls the wrong function, a missing vibration call.
- In Smart QR
__tests__/ScannerScreen-test.tsx- Run it
npm test
- 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:
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.
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.
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.
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.
1 { 2 "name": "smart-qr-scanner", 3 "version": "1.0.0", 4 "main": "index.ts", 5 "dependencies": { 6 "expo": "~58.0.26", 7 "expo-camera": "~58.0.14", 8 "expo-haptics": "~58.0.8", 9 "expo-status-bar": "~58.0.5", 10 "react": "19.3.0", 11 "react-native": "0.88.1" 12 }, 13 "devDependencies": { 14 "@testing-library/react-native": "^14.1.0", 15 "@types/jest": "^30.0.0", 16 "@types/react": "~19.3.0", 17 "jest": "~30.5.2", 18 "jest-expo": "~58.0.15", 19 "test-renderer": "^1.3.1", 20 "typescript": "~6.0.3" 21 }, 22 "scripts": { 23 "start": "expo start", 24 "android": "expo start --android", 25 "ios": "expo start --ios", 26 "web": "expo start --web", 27 "test": "jest", 28 "test:watch": "jest --watchAll" 29 }, 30 "private": true, 31 "jest": { 32 "preset": "jest-expo" 33 } 34 }
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.
Now explaining · lines 13–21Jest
devDependencies: tools for your computer
devDependencies are tools used only on a computer — the test tools. They never go into the app.
Now explaining · line 14React Native Testing Library
React Native Testing Library
Draws components in tests.
Now explaining · line 15Jest
Jest’s types
The TypeScript types of Jest, so the editor knows describe, test and expect.
Now explaining · lines 17–18Jest
Jest and jest-expo
Jest itself, and jest-expo: Jest’s settings for Expo projects.
Now explaining · line 19React Native Testing Library
test-renderer
test-renderer: what React Native Testing Library 14 uses to draw components without a phone.
Now explaining · line 27Jest
npm test
npm test runs jest once: every test, then a summary.
Now explaining · line 28Jest
npm run test:watch
npm run test:watch keeps Jest open and runs the tests again after every save.
Now explaining · lines 31–33Jest
The jest-expo preset
Jest’s settings: use the jest-expo preset (a ready-made set of settings).
- lines 5–12 dependencies: what the app needs on the phone
dependencies go into the app.
expo-cameraandexpo-hapticsare here. - lines 13–21 devDependencies: tools for your computer
devDependencies are tools used only on a computer — the test tools. They never go into the app.
- line 14 React Native Testing Library
Draws components in tests.
- line 15 Jest’s types
The TypeScript types of Jest, so the editor knows
describe,testandexpect. - lines 17–18 Jest and jest-expo
Jest itself, and
jest-expo: Jest’s settings for Expo projects. - line 19 test-renderer
test-renderer: what React Native Testing Library 14 uses to draw components without a phone. - line 27
npm testnpm testrunsjestonce: every test, then a summary. - line 28
npm run test:watchnpm run test:watchkeeps Jest open and runs the tests again after every save. - lines 31–33 The jest-expo preset
Jest’s settings: use the
jest-expopreset (a ready-made set of settings).
1 { 2 "extends": "expo/tsconfig.base", 3 "compilerOptions": { 4 "strict": true, 5 "types": ["jest"] 6 } 7 }
Now explaining · line 2Expo
Expo’s settings
Start from Expo’s TypeScript settings.
Now explaining · line 4
strict
strict: TypeScript checks everything it can.
Now explaining · line 5Jest
Jest’s names everywhere
"types": ["jest"]: load Jest’s types everywhere, so test files can use describe, test and expect without importing them.
- line 2 Expo’s settings
Start from Expo’s TypeScript settings.
- line 4 strict
strict: TypeScript checks everything it can. - line 5 Jest’s names everywhere
"types": ["jest"]: load Jest’s types everywhere, so test files can usedescribe,testandexpectwithout importing them.
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 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:
1 import { parseScan } from '../src/scan/parseScan'; 2 3 describe('parseScan', () => { 4 test('a website link is a website', () => { 5 const result = parseScan('https://expo.dev'); 6 expect(result).toEqual({ ok: true, kind: 'website', label: 'Website', value: 'https://expo.dev' }); 7 }); 8 9 test('a Wi-Fi code is a Wi-Fi network', () => { 10 const result = parseScan('WIFI:S:Lab-5G;T:WPA;P:secret123;;'); 11 expect(result.ok).toBe(true); 12 if (result.ok) expect(result.kind).toBe('wifi'); 13 }); 14 15 test('email and phone codes are recognized', () => { 16 expect(parseScan('mailto:ta@example.com')).toMatchObject({ ok: true, kind: 'email' }); 17 expect(parseScan('tel:+15555550100')).toMatchObject({ ok: true, kind: 'phone' }); 18 }); 19 20 test('anything else is plain text', () => { 21 expect(parseScan('Room 3.12')).toMatchObject({ ok: true, kind: 'text', value: 'Room 3.12' }); 22 }); 23 24 test('spaces around the code are removed', () => { 25 expect(parseScan(' https://expo.dev ')).toMatchObject({ value: 'https://expo.dev' }); 26 }); 27 28 test('an empty code is an error', () => { 29 expect(parseScan('')).toEqual({ ok: false, error: 'This QR code is empty.' }); 30 expect(parseScan(' ')).toEqual({ ok: false, error: 'This QR code is empty.' }); 31 expect(parseScan(null)).toEqual({ ok: false, error: 'This QR code is empty.' }); 32 }); 33 34 test('a very long code is an error', () => { 35 const result = parseScan('x'.repeat(501)); 36 expect(result.ok).toBe(false); 37 }); 38 });
Now explaining · line 1Jest
Import the code to test
Tests import your code like any other file.
Jest found the file and ran it.
Now explaining · line 3Jest
describe: a group
describe('parseScan', …): a group. Its name appears in the output above the tests it holds.
The group’s name is printed above its tests.
Now explaining · line 4Jest
test: one test, named as a sentence
test(name, function): one test. The name says what should happen, as a sentence — it is what you read in the output.
Now explaining · line 5Jest
Run the code with one input…
Call parseScan with one input, and keep what it gives in result.
Now explaining · line 6Jest
…and check the output
toEqual compares every field of the object. One different field = FAIL.
Now explaining · lines 11–12Jest
toBe: one value
toBe compares one value. if (result.ok) tells TypeScript the result has a kind.
Now explaining · lines 16–17Jest
toMatchObject: only the fields you list
toMatchObject checks only the fields you list; the others may be anything.
Now explaining · lines 29–31Jest
Several checks in one test
Several expect lines in one test: the test passes only if all of them pass.
Now explaining · line 35Jest
A text of 501 letters
'x'.repeat(501): a text of 501 x’s, one more than the limit.
All seven passed.
- line 1 Import the code to test
Tests import your code like any other file.
- line 3
describe: a groupdescribe('parseScan', …): a group. Its name appears in the output above the tests it holds. - line 4
test: one test, named as a sentencetest(name, function): one test. The name says what should happen, as a sentence — it is what you read in the output. - line 5 Run the code with one input…
Call
parseScanwith one input, and keep what it gives inresult. - line 6 …and check the output
toEqualcompares every field of the object. One different field = FAIL. - lines 11–12
toBe: one valuetoBecompares one value.if (result.ok)tells TypeScript the result has akind. - lines 16–17
toMatchObject: only the fields you listtoMatchObjectchecks only the fields you list; the others may be anything. - lines 29–31 Several checks in one test
Several
expectlines in one test: the test passes only if all of them pass. - line 35 A text of 501 letters
'x'.repeat(501): a text of 501 x’s, one more than the limit.
Run it yourself, then change one word of a test and run it again:
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:
Read it in three places:
● parseScan › an empty code is an error
The group and the test name.
− Expected · + Received
− lines: what the test wanted. + lines: what your code gave.
> 29 | … ^
The line of the test file that failed, and the column (29:27).
④ Your turn · Exercise 10
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);parseScanreturn { ok: true, kind: 'wifi', label: 'Wi-Fi network', value };✓ PASS — must passreturn { ok: true, kind: 'text', label: 'Text', value };✕ FAIL — your test caught the bug ✓✓ PASS — the test cannot see the bug ✕- 1 / 5You write a test for the Wi-Fi code
Your test gives
parseScana 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. - 2 / 5Run 1: on the real parseScan → must PASS
First on the real
parseScan. A good test passes here: the real code is right. A test that fails on the real code is a wrong test. - 3 / 5Run 2: on a broken copy
Then Check makes a broken copy of
parseScan: one line changed so a Wi-Fi code comes back askind: 'text'. This is the kind of mistake a real change can make. - 4 / 5A strong test → FAILS on the broken copy ✓
expect(result.kind).toBe('wifi')sees'text'and fails. That is what we want: your test caught the bug. Check line: “your tests fail when parseScan calls a Wi-Fi code plain text” ✓. - 5 / 5A weak test → still PASSES ✕
expect(result.ok).toBe(true)only checksok. The broken copy still givesok: true, so this test passes on both — it cannot see the bug. Check says: “Your tests still pass on a broken …”. Fix: expect the exact value.
Choose the matcher by what you want to prove:
toEqual(…)
Every field must be the same: expect(parseScan('')).toEqual({ ok: false, error: 'This QR code is empty.' }).
toBe(…)
One value, like a kind: if (result.ok) expect(result.kind).toBe('wifi').
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).
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';jest.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);- 1 / 5A test runs on a computer
ScannerScreenimportsexpo-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). - 2 / 5
jest.mock: swap a package for a fakejest.mock('expo-camera', () => require('../test-utils/fakeCamera'))— in this test file, everyimport … from 'expo-camera'gets the fake file instead. The screen’s code does not change at all. - 3 / 5The fake camera: buttons that “scan”
The fake
CameraViewdraws two buttons. Pressing Fake scan: website callsonBarcodeScannedwith{ type: 'qr', data: 'https://expo.dev' }— the same shape a real camera gives. The test decides what is scanned. - 4 / 5
jest.fn(): the test decides the answerIn the fake file
useCameraPermissions = jest.fn(): a mock function. Each test sets what it returns withmockReturnValue(…)— granted, not granted, or refused for good — so one screen can be tested in every state. - 5 / 5
jest.mock('expo-haptics'): calls are rememberedWith no second argument, every function of the package becomes a mock: nothing vibrates, but each call is remembered.
toHaveBeenCalledWith(…Success)checks that the screen asked for the success vibration.
③ The code, line by line
The fake camera — a finished file:
1 import { Pressable, Text, View } from 'react-native'; 2 3 // A fake expo-camera for tests: no real camera, and the test decides what is "scanned". 4 export const useCameraPermissions = jest.fn(); 5 6 type Props = { onBarcodeScanned?: (scan: { type: string; data: string }) => void }; 7 8 export function CameraView({ onBarcodeScanned }: Props) { 9 return ( 10 <View> 11 <Pressable testID="fake-scan-website" onPress={() => onBarcodeScanned?.({ type: 'qr', data: 'https://expo.dev' })}> 12 <Text>Fake scan: website</Text> 13 </Pressable> 14 <Pressable testID="fake-scan-empty" onPress={() => onBarcodeScanned?.({ type: 'qr', data: ' ' })}> 15 <Text>Fake scan: empty code</Text> 16 </Pressable> 17 </View> 18 ); 19 }
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.
Now explaining · line 4Jest
A mock function
useCameraPermissions becomes jest.fn(): a mock function. Each test decides what it returns.
Now explaining · line 6React
Only the prop the tests need
The fake camera takes only the prop the tests need: onBarcodeScanned.
Now explaining · lines 11–13React Native
A button that “scans” a website
Pressing it calls onBarcodeScanned with the same shape a real camera gives (type and data): https://expo.dev.
A test presses it by its testID.
Now explaining · lines 14–16React Native
A button that scans an empty code
A second button scans an empty code (three spaces).
- line 3 A stand-in for expo-camera
This file pretends to be
expo-camerain the tests. It exports the same names the scanner imports. - line 4 A mock function
useCameraPermissionsbecomesjest.fn(): a mock function. Each test decides what it returns. - line 6 Only the prop the tests need
The fake camera takes only the prop the tests need:
onBarcodeScanned. - lines 11–13 A button that “scans” a website
Pressing it calls
onBarcodeScannedwith the same shape a real camera gives (typeanddata):https://expo.dev. - lines 14–16 A button that scans an empty code
A second button scans an empty code (three spaces).
The component test, test by test. The phone shows the screen the test draws; under it, what Jest prints:
1 import { render, screen, userEvent } from '@testing-library/react-native'; 2 import { useCameraPermissions } from 'expo-camera'; 3 import * as Haptics from 'expo-haptics'; 4 import ScannerScreen from '../src/screens/ScannerScreen'; 5 6 jest.mock('expo-camera', () => require('../test-utils/fakeCamera')); 7 jest.mock('expo-haptics'); 8 9 const askForCamera = jest.fn(); 10 11 function givePermission(permission: { granted: boolean; canAskAgain: boolean }) { 12 jest.mocked(useCameraPermissions).mockReturnValue([permission as any, askForCamera, jest.fn()]); 13 } 14 15 beforeEach(() => { 16 jest.clearAllMocks(); 17 }); 18 19 test('asks for the camera when permission is not granted yet', async () => { 20 givePermission({ granted: false, canAskAgain: true }); 21 await render(<ScannerScreen onBack={jest.fn()} />); 22 23 expect(screen.getByText('Camera permission needed')).toBeOnTheScreen(); 24 25 const user = userEvent.setup(); 26 await user.press(screen.getByRole('button', { name: 'Allow camera' })); 27 expect(askForCamera).toHaveBeenCalledTimes(1); 28 }); 29 30 test('sends the user to the settings when the phone will not ask again', async () => { 31 givePermission({ granted: false, canAskAgain: false }); 32 await render(<ScannerScreen onBack={jest.fn()} />); 33 34 expect(screen.getByRole('button', { name: 'Open settings' })).toBeOnTheScreen(); 35 expect(screen.queryByRole('button', { name: 'Allow camera' })).not.toBeOnTheScreen(); 36 }); 37 38 test('a scanned website shows its result and the success vibration', async () => { 39 givePermission({ granted: true, canAskAgain: true }); 40 await render(<ScannerScreen onBack={jest.fn()} />); 41 42 const user = userEvent.setup(); 43 await user.press(screen.getByTestId('fake-scan-website')); 44 45 expect(await screen.findByText('https://expo.dev')).toBeOnTheScreen(); 46 expect(screen.getByText('Website')).toBeOnTheScreen(); 47 expect(Haptics.notificationAsync).toHaveBeenCalledWith(Haptics.NotificationFeedbackType.Success); 48 }); 49 50 test('an empty code shows an error and the error vibration', async () => { 51 givePermission({ granted: true, canAskAgain: true }); 52 await render(<ScannerScreen onBack={jest.fn()} />); 53 54 const user = userEvent.setup(); 55 await user.press(screen.getByTestId('fake-scan-empty')); 56 57 expect(await screen.findByText('This QR code is empty.')).toBeOnTheScreen(); 58 expect(Haptics.notificationAsync).toHaveBeenCalledWith(Haptics.NotificationFeedbackType.Error); 59 }); 60 61 test('Scan again goes back to the camera', async () => { 62 givePermission({ granted: true, canAskAgain: true }); 63 await render(<ScannerScreen onBack={jest.fn()} />); 64 65 const user = userEvent.setup(); 66 await user.press(screen.getByTestId('fake-scan-website')); 67 await user.press(await screen.findByRole('button', { name: 'Scan again' })); 68 69 expect(screen.getByTestId('fake-scan-website')).toBeOnTheScreen(); 70 });
On the lab phone now






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.
Now explaining · lines 2–4Jest
What the test uses
The hook and the haptics (both replaced below), and the screen to test.
Now explaining · line 6Jest
The fake camera
jest.mock('expo-camera', …): in this file, every import … from 'expo-camera' gets the fake camera instead.
Now explaining · line 7Jest
Fake haptics
jest.mock('expo-haptics') with no second argument: every function of the package becomes a mock that only remembers its calls.
Now explaining · line 9Jest
A mock for requestPermission
A mock function the tests use as requestPermission, to check if the screen asked.
Now explaining · lines 11–13Jest
givePermission: choose the answer
givePermission: a helper that makes the fake hook return a chosen permission. jest.mocked(…) tells TypeScript it is a mock.
Now explaining · lines 15–17Jest
beforeEach: a clean start
beforeEach: runs before every test. clearAllMocks forgets the calls of the last test.
Now explaining · lines 20–21React Native Testing Library
Test 1 · arrange: not granted, then draw
Arrange: not granted, but the phone may ask. Then draw the screen (await render).
The test drew this screen (in memory, not on a phone).
Now explaining · line 23React Native Testing Library
Test 1 · assert: the text is there
getByText finds the element with this whole text, and fails at once if it is not there; toBeOnTheScreen() checks that it is shown.
Now explaining · lines 25–27React Native Testing Library
Test 1 · act and assert: press Allow camera
Press Allow camera — found by its role and name, like a screen reader finds it — and check the screen called requestPermission once.
Now explaining · lines 31–35React Native Testing Library
Test 2 · refused for good: Open settings
canAskAgain: false: Open settings must be there. queryByRole returns null instead of failing, so .not.toBeOnTheScreen() can check that Allow camera is gone.
Now explaining · lines 39–43React Native Testing Library
Test 3 · granted: scan a website
Granted this time: the fake camera appears. Press its Fake scan: website button (by its testID).
Now explaining · lines 45–47React Native Testing Library
Test 3 · wait for the result and the vibration
findByText waits for the result card. Then: the label is there, and the success vibration was asked for.
Now explaining · lines 55–58React Native Testing Library
Test 4 · an empty code: the error
The other fake button scans an empty code: the error message, and the error vibration.
Now explaining · lines 66–69React Native Testing Library
Test 5 · Scan again
Scan, press Scan again, and check the fake camera is back. The runner also prints the console.log lines your code wrote while the tests ran (Scanned: https://expo.dev), with the file and the line, as Jest does.
The camera is back.
- line 1 The tools of React Native Testing Library
renderdraws a component,screenfinds things on it,userEventpresses like a finger. - lines 2–4 What the test uses
The hook and the haptics (both replaced below), and the screen to test.
- line 6 The fake camera
jest.mock('expo-camera', …): in this file, everyimport … from 'expo-camera'gets the fake camera instead. - line 7 Fake haptics
jest.mock('expo-haptics')with no second argument: every function of the package becomes a mock that only remembers its calls. - line 9 A mock for requestPermission
A mock function the tests use as
requestPermission, to check if the screen asked. - lines 11–13 givePermission: choose the answer
givePermission: a helper that makes the fake hook return a chosen permission.jest.mocked(…)tells TypeScript it is a mock. - lines 15–17 beforeEach: a clean start
beforeEach: runs before every test.clearAllMocksforgets the calls of the last test. - lines 20–21 Test 1 · arrange: not granted, then draw
Arrange: not granted, but the phone may ask. Then draw the screen (
await render). - line 23 Test 1 · assert: the text is there
getByTextfinds the element with this whole text, and fails at once if it is not there;toBeOnTheScreen()checks that it is shown. - lines 25–27 Test 1 · act and assert: press Allow camera
Press Allow camera — found by its role and name, like a screen reader finds it — and check the screen called
requestPermissiononce. - lines 31–35 Test 2 · refused for good: Open settings
canAskAgain: false: Open settings must be there.queryByRolereturnsnullinstead of failing, so.not.toBeOnTheScreen()can check that Allow camera is gone. - lines 39–43 Test 3 · granted: scan a website
Granted this time: the fake camera appears. Press its Fake scan: website button (by its
testID). - lines 45–47 Test 3 · wait for the result and the vibration
findByTextwaits for the result card. Then: the label is there, and the success vibration was asked for. - lines 55–58 Test 4 · an empty code: the error
The other fake button scans an empty code: the error message, and the error vibration.
- lines 66–69 Test 5 · Scan again
Scan, press Scan again, and check the fake camera is back. The runner also prints the
console.loglines your code wrote while the tests ran (Scanned: https://expo.dev), with the file and the line, as Jest does.
④ Your turn · Exercise 12
Each line of this test has one job: find, press or check. Match them.
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);});
- 1 / 6Arrange ① — the answer of the permission
First, prepare the world of the test.
givePermissionmakes the fake hook answer “granted”. It must come beforerender: the screen reads the permission while it is drawn. - 2 / 6Arrange ② — draw the screen
render(<ScannerScreen … />)draws the screen inside the test, with the fake camera. Nothing is on a real phone: React Native Testing Library keeps the screen in memory. - 3 / 6Act — press like a user
userEvent.setup()makes a pretend user.user.press(…)presses the element whosetestIDisfake-scan-website: the fake camera “reads”https://expo.dev. - 4 / 6Assert ① — wait for the result
The result card appears a moment after the press.
findByTextwaits for it (up to a second);getByTextwould look only once, too early.toBeOnTheScreen()checks it is shown. - 5 / 6Assert ② — the label and the vibration
Now the card is there, so
getByText('Website')can look at once.toHaveBeenCalledWith(…Success)checks the mock ofexpo-hapticswas asked for the success vibration. All three checks pass → ✓. - 6 / 6Why this order
Arrange → act → assert. Prepare, then do what a user does, then check. Checking before pressing, or drawing before the permission is set, would test the wrong screen.
④ Your turn · Exercise 13
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, thenexpect(Haptics.notificationAsync).toHaveBeenCalledWith(Haptics.NotificationFeedbackType.Error).
The two screens your new tests draw and check — the same screens as on the lab phone:
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
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:
- The finger presses ▶ Run flow.
- Nobody touches the phone: Maestro taps Start scanning, Allow camera, the dialog, and Use sample QR by itself.
- 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
- 1 / 11Which app, then the steps
appIdnames 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-. - 2 / 11
stopApp: start from scratchClose the app first, so every run starts the same way, whatever the last run left on the screen.
- 3 / 11
openLink: open your projectOpen the project in Expo Go.
${APP_URL}is filled in when you start the flow (maestro test … -e APP_URL=exp://…). On the lab page it opens the app on the lab phone. - 4 / 11
extendedWaitUntil: wait for the first screenThe first load of the JavaScript can be slow. Maestro waits until Start scanning is
visible— at mosttimeout: 60000milliseconds (60 seconds) — then goes on. - 5 / 11
tapOn: "Start scanning": tap like a fingerMaestro finds the element whose whole text is “Start scanning” and taps it. The scanner opens and asks for the camera.
- 6 / 11
optional: true: tap it if it is thereA new phone shows Allow camera and the phone’s dialog. If the camera was allowed in an earlier run, these screens never come.
optional: truesays: tap it if it is there — if not, go on without failing (WARNED, not FAILED). - 7 / 11The dialog: “While using the app”
The same for the phone’s own dialog. Maestro taps the system dialog just like the app’s buttons.
- 8 / 11
tapOn: id: "sample-scan": tap by ididfinds the element by itstestID— invisible to users, and it does not change when the button’s text changes. Use sample QR “scans”https://expo.dev. - 9 / 11
assertVisible: check what a user seesAn assertion: the step fails if
https://expo.devis not on the screen (Maestro waits a few seconds first). The second one checks the Scan again button by its id. - 10 / 11
takeScreenshot: a picture as proofSaves a picture of the screen as
scan-result.png. The flow passed: from a closed app to the result card, without a person touching the phone. - 11 / 11Every step COMPLETED
Maestro prints one line per step. COMPLETED — done; WARNED — an optional step was skipped; FAILED — Maestro stops there and says why.
③ The code, line by line
1 appId: host.exp.exponent 2 --- 3 - stopApp 4 - openLink: ${APP_URL} 5 - extendedWaitUntil: 6 visible: "Start scanning" 7 timeout: 60000 8 - tapOn: "Start scanning" 9 - tapOn: 10 text: "Allow camera" 11 optional: true 12 - tapOn: 13 text: "While using the app" 14 optional: true 15 - tapOn: 16 id: "sample-scan" 17 - assertVisible: "https://expo.dev" 18 - assertVisible: 19 id: "scan-again" 20 - takeScreenshot: scan-result
On the lab phone now




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.
Now explaining · line 2Maestro
---
--- ends the settings. Everything below is a step.
Now explaining · line 3Maestro
stopApp
stopApp: close the app, so every run starts the same way.
Now explaining · line 4Maestro
openLink
openLink: open your project (in Expo Go). ${APP_URL} is filled in from the command line (-e APP_URL=…).
Now explaining · lines 5–7Maestro
extendedWaitUntil
Wait up to 60 seconds (60000 ms) until Start scanning is visible: the first load of the JavaScript can be slow.
Now explaining · line 8Maestro
tapOn: "Start scanning"
tapOn: "Start scanning": tap the element with this text. The text must match the element’s whole text.
Now explaining · lines 9–14Maestro
optional: true
Tap Allow camera and the dialog’s While using the app — optional: true means: if they are not there (the camera was allowed before), go on without failing.
Now explaining · lines 15–16Maestro
id: "sample-scan"
id: "sample-scan": tap the element whose testID is sample-scan. ids do not change when you change a button’s text.
Now explaining · line 17Maestro
assertVisible
assertVisible: the step fails if this text is not on the screen. Maestro waits a few seconds first.
Now explaining · lines 18–19Maestro
Check a button by its id
Check the Scan again button by its id.
Now explaining · line 20Maestro
takeScreenshot
Save a picture of the screen as scan-result.png.
- line 1
appId: which appappId: which app the flow drives. In Expo Go, the app is Expo Go itself:host.exp.exponent. - line 2
------ends the settings. Everything below is a step. - line 3
stopAppstopApp: close the app, so every run starts the same way. - line 4
openLinkopenLink: open your project (in Expo Go).${APP_URL}is filled in from the command line (-e APP_URL=…). - lines 5–7
extendedWaitUntilWait up to 60 seconds (60000 ms) until Start scanning is visible: the first load of the JavaScript can be slow.
- line 8
tapOn: "Start scanning"tapOn: "Start scanning": tap the element with this text. The text must match the element’s whole text. - lines 9–14
optional: trueTap Allow camera and the dialog’s While using the app —
optional: truemeans: if they are not there (the camera was allowed before), go on without failing. - lines 15–16
id: "sample-scan"id: "sample-scan": tap the element whosetestIDissample-scan. ids do not change when you change a button’s text. - line 17
assertVisibleassertVisible: the step fails if this text is not on the screen. Maestro waits a few seconds first. - lines 18–19 Check a button by its id
Check the Scan again button by its id.
- line 20
takeScreenshotSave a picture of the screen as
scan-result.png.
④ Your turn · Exercise 15
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 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):
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:
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.
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 · Your project
- 2 · Expo’s build server
- 3 · The file you get
- 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.)
| What | APK.apk | AAB.aab |
|---|---|---|
| Install with a tap | Yesbetter here | No |
| Google Play accepts it for new apps | No | Yesbetter here |
| Size on each phone | Everything for every phone | Google Play builds a smaller APK for each phonebetter here |
| In Smart QR | The preview profile | The production profile |
Which one would you use?
- Your classmates test the app this week.
An APK from an install link, no store needed.
- The app goes to Google Play.
Google Play wants an app bundle.
② How it works: Submit and Update
eas submit uploads a finished production build to a store:
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.
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:
eas updateupload the JavaScript and images of the project--channel previewto the builds made with the preview profile--message "…"a note for you: what changed--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- 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. - 2 / 5A JavaScript change →
eas updateYou fix a bug in
parseScan.ts— only JavaScript.eas update --channel previewuploads the new JavaScript to Expo’s servers, for the builds made with the preview profile. - 3 / 5Next start: the phone downloads it
The next time the app starts, it asks Expo for an update, downloads the new JavaScript, and runs it. No store review, no new install.
- 4 / 5A native change cannot travel in an update
A new native package, a new permission text in
app.json, a new icon: these change the native layer, and an update only carries JavaScript and images. The phone still runs the old native code. - 5 / 5So: a new build
eas buildmakes a new app file with a new runtime version. People install it; from then on, updates for the new runtime version reach it. An update never reaches a build with a different runtime version.
④ Your turn · Exercise 17
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:
1 { 2 "cli": { 3 "version": ">= 27.11.0", 4 "appVersionSource": "remote" 5 }, 6 "build": { 7 "development": { 8 "developmentClient": true, 9 "distribution": "internal" 10 }, 11 "preview": { 12 "distribution": "internal", 13 "android": { 14 "buildType": "apk" 15 } 16 }, 17 "production": { 18 "autoIncrement": true 19 } 20 }, 21 "submit": { 22 "production": {} 23 } 24 }
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.
Now explaining · line 6EAS
One entry per profile
build: one entry per profile. You choose one with --profile.
Now explaining · lines 7–10EAS
development
development: a development build — your own Expo Go with your native packages — shared by link (internal).
Now explaining · lines 11–16EAS
preview: an APK, by link
preview: the real app, shared by link. "buildType": "apk" gives a file that installs with a tap.
Now explaining · lines 17–19EAS
production: for the stores
production: for the stores. No buildType, so Android gets an AAB. autoIncrement raises the build number on every build.
Now explaining · lines 21–23EAS
submit
submit: settings for eas submit. The empty production profile uses the defaults.
- lines 2–5 The EAS CLI and the version numbers
cli: the EAS CLI version this project needs, andappVersionSource: "remote": EAS keeps the build numbers on its servers. - line 6 One entry per profile
build: one entry per profile. You choose one with--profile. - lines 7–10 development
development: a development build — your own Expo Go with your native packages — shared by link (
internal). - lines 11–16 preview: an APK, by link
preview: the real app, shared by link.
"buildType": "apk"gives a file that installs with a tap. - lines 17–19 production: for the stores
production: for the stores. No buildType, so Android gets an AAB.
autoIncrementraises the build number on every build. - lines 21–23 submit
submit: settings foreas submit. The emptyproductionprofile uses the defaults.
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:
1 { 2 "expo": { 3 "name": "Smart QR", 4 "slug": "smart-qr-scanner", 5 "version": "1.0.0", 6 "orientation": "portrait", 7 "icon": "./assets/icon.png", 8 "userInterfaceStyle": "dark", 9 "ios": { 10 "supportsTablet": true, 11 "bundleIdentifier": "com.yourname.smartqr" 12 }, 13 "android": { 14 "adaptiveIcon": { 15 "backgroundColor": "#E6F4FE", 16 "foregroundImage": "./assets/android-icon-foreground.png", 17 "backgroundImage": "./assets/android-icon-background.png", 18 "monochromeImage": "./assets/android-icon-monochrome.png" 19 }, 20 "predictiveBackGestureEnabled": false, 21 "package": "com.yourname.smartqr", 22 "permissions": [ 23 "android.permission.CAMERA" 24 ] 25 }, 26 "web": { 27 "favicon": "./assets/favicon.png" 28 }, 29 "plugins": [ 30 [ 31 "expo-camera", 32 { 33 "cameraPermission": "Allow $(PRODUCT_NAME) to use the camera to read QR codes.", 34 "recordAudioAndroid": false 35 } 36 ] 37 ] 38 } 39 }
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.
Now explaining · lines 7–8Expo
Icon and style
The icon file, and "dark": the app always uses a dark style.
Now explaining · lines 9–12Expo
iPhone: the bundle identifier
iPhone settings. bundleIdentifier is the app’s unique id in the App Store. Change yourname to your own name before your first build (Part 9).
Now explaining · lines 14–19Expo
Android’s icon
Android’s icon: a background and a foreground layer, so each phone can cut it into its own shape.
Now explaining · line 21Expo
Android: the package
package: the Android app’s unique id in Google Play. It can never change after the first upload.
Now explaining · lines 22–24expo-camera
Permissions
The Android permissions the app needs. expo-camera adds the CAMERA permission by itself; writing it here makes it visible.
Now explaining · lines 29–31expo-camera
The camera’s config plugin
The expo-camera config plugin: code that edits the native project during a build.
Now explaining · line 33expo-camera
The iPhone dialog’s sentence
The sentence an iPhone shows in its camera dialog. $(PRODUCT_NAME) is replaced by the app’s name. Android always uses its own sentence.
Now explaining · line 34expo-camera
No microphone
recordAudioAndroid: false: Smart QR never records video, so it does not ask for the microphone on Android.
- lines 3–5 Name, slug, version
The app’s name on the phone (“Smart QR”), its short name in URLs (
slug), and its version for users. - lines 7–8 Icon and style
The icon file, and
"dark": the app always uses a dark style. - lines 9–12 iPhone: the bundle identifier
iPhone settings.
bundleIdentifieris the app’s unique id in the App Store. Changeyournameto your own name before your first build (Part 9). - lines 14–19 Android’s icon
Android’s icon: a background and a foreground layer, so each phone can cut it into its own shape.
- line 21 Android: the package
package: the Android app’s unique id in Google Play. It can never change after the first upload. - lines 22–24 Permissions
The Android permissions the app needs.
expo-cameraadds the CAMERA permission by itself; writing it here makes it visible. - lines 29–31 The camera’s config plugin
The
expo-cameraconfig plugin: code that edits the native project during a build. - line 33 The iPhone dialog’s sentence
The sentence an iPhone shows in its camera dialog.
$(PRODUCT_NAME)is replaced by the app’s name. Android always uses its own sentence. - line 34 No microphone
recordAudioAndroid: false: Smart QR never records video, so it does not ask for the microphone on Android.
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
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.bundleIdentifierandandroid.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: changeyournamenow. - The preview profile —
eas build:configurewriteseas.jsonwith 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" }}
- a , between items
- no , after the last item
- texts in " "
- keys in " "
- 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. - 2 / 6Mistake 1: a missing comma
After
"internal"the next item starts, so a,must come between them. The error names the place: line 3, the item after the missing comma. - 3 / 6Mistake 2: a comma after the last item
"apk",is the last item of its object, so no comma after it. JavaScript allows it; JSON does not. - 4 / 6Mistake 3: single quotes
Texts need double quotes:
"apk", never'apk'. - 5 / 6Mistake 4: a key without quotes
In JavaScript
{ buildType: "apk" }works. In JSON every key is a text too:"buildType". - 6 / 6Fixed: valid JSON
All four rules kept. EAS can read the file now — and so can Check, which first tests that your
app.jsonandeas.jsonare valid JSON.
④ Your turn · Exercise 19
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:
Then the build itself. These lines are real, from the build of Smart QR made for this lab (only the account name was changed):
② How it works
What happened, in order:
- versionCode 1 — Android’s build number. EAS keeps it (
appVersionSource: "remote"). - Keystore — EAS made the signing key and keeps it. Every later build is signed with it.
- Uploaded — the project (1.2 MB without
node_modules) went to Expo’s servers. - 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:
Build artifact · APK · Succeeded. Anyone with the link can install it on Android. (The account name is blurred in this picture.)
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
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.
② 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
WIFI:S:Lab-5G;T:WPA;P:secret123;;'S:Lab-5G''T:WPA''P:secret123''''''S:Lab-5G''Lab-5G'- 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. - 2 / 6
value.slice(5): drop “WIFI:”slice(5)gives the text from position 5 on. Positions start at 0, so the 5 lettersW I F I :(0–4) are left out. - 3 / 6
.split(';'): cut at every “;”split(';')cuts the text at each;and gives a list (an array). The two;;at the end make two empty items. - 4 / 6
fields.find(…): the field that starts with “S:”findgoes through the list and gives the first item for which the test is true:field.startsWith('S:'). If no item matches,findgivesundefined. - 5 / 6
nameField.slice(2): drop “S:”slice(2)leaves out the two lettersS:→Lab-5G. (nameField ? … : ''first checks a field was found.) - 6 / 6
name || 'Hidden network': never empty||gives the left side when it has a value, otherwise the right side. A code with noS:field (a hidden network) shows Hidden network. The password field is never used.
③ The code, line by line
The Wi-Fi branch of parseScan.ts, fixed. The phone shows the card it makes:
1 if (lower.startsWith('wifi:')) { 2 // "WIFI:S:Lab-5G;T:WPA;P:secret123;;" → the text after "WIFI:", cut at each ";" 3 const fields = value.slice(5).split(';'); 4 // the field that starts with "S:" holds the network name ("S:Lab-5G") 5 const nameField = fields.find((field) => field.startsWith('S:')); 6 const name = nameField ? nameField.slice(2) : ''; 7 return { ok: true, kind: 'wifi', label: 'Wi-Fi network', value: name || 'Hidden network' }; 8 }
On the lab phone now


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.
Now explaining · lines 2–3React
Cut the text into fields
value.slice(5) drops the 5 letters of WIFI:; .split(';') cuts the rest at each ; into a list: ['S:Lab-5G', 'T:WPA', 'P:secret123', '', ''].
Now explaining · lines 4–5React
Find the name field
find gives the first field that starts with S: — or undefined if there is none.
Now explaining · line 6React
Drop “S:”
If it was found, drop its first 2 letters (S:): Lab-5G. If not, an empty text.
Now explaining · line 7React
Return the name — never the password
Return the name only. name || 'Hidden network': an empty name falls back to the text “Hidden network”. The password is never returned.
After the fix: only the network name.
- line 1 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. - lines 2–3 Cut the text into fields
value.slice(5)drops the 5 letters ofWIFI:;.split(';')cuts the rest at each;into a list:['S:Lab-5G', 'T:WPA', 'P:secret123', '', '']. - lines 4–5 Find the name field
findgives the first field that starts withS:— orundefinedif there is none. - line 6 Drop “S:”
If it was found, drop its first 2 letters (
S:):Lab-5G. If not, an empty text. - line 7 Return the name — never the password
Return the name only.
name || 'Hidden network': an empty name falls back to the text “Hidden network”. The password is never returned.
A fix is finished when a test proves it. Add this test to __tests__/parseScan-test.ts:
1 test('a Wi-Fi code shows the network name, never the password', () => { 2 const result = parseScan('WIFI:S:Lab-5G;T:WPA;P:secret123;;'); 3 expect(result).toMatchObject({ ok: true, kind: 'wifi', value: 'Lab-5G' }); 4 });
Now explaining · line 1Jest
Say what must happen
The name says the rule: the network name, never the password.
Now explaining · line 2Jest
The same Wi-Fi code
The same Wi-Fi code as on the lab phone.
Now explaining · line 3Jest
Expect the name as the value
toMatchObject checks kind: 'wifi' and value: 'Lab-5G'. On the old code the value was the whole text, so this test fails there: it proves the fix.
Passes on the fixed code — and fails on the old one.
- line 1 Say what must happen
The name says the rule: the network name, never the password.
- line 2 The same Wi-Fi code
The same Wi-Fi code as on the lab phone.
- line 3 Expect the name as the value
toMatchObjectcheckskind: 'wifi'andvalue: 'Lab-5G'. On the old code the value was the whole text, so this test fails there: it proves the fix.
④ Your turn · Exercise 21
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
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
Three layers
- unit tests for logic (Jest)
- component tests with fakes (React Native Testing Library)
- an end-to-end flow (Maestro)
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.jsonhas your own id andeas.jsonmakes a preview APK
Questions to check yourself
- Why does
useCameraPermissions()givenullfirst, and what should the screen show then? - What is the difference between
canAskAgain: trueandfalse, and what does the app show for each? - Why is the scan lock a
useRefand not auseState? - Why does Smart QR play the success vibration in ResultCard and not in
handleScan? - 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? - In a Jest failure, which lines come from your code and which from the test?
- Why does the Maestro flow use
optional: truefor the permission dialog? - When do you need a new build, and when is
eas updateenough?
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
Smart QR · Start scanning
Camera permission needed · Allow camera
Point the camera at a QR code
✓ WEBSITE · https://expo.dev · Open link · Scan again
Tests: 13 passed, 13 total
Take screenshot scan-result... COMPLETED
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”
The screen shows CameraView before the user allowed the camera.
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
The user refused twice before, so the phone no longer asks (canAskAgain is false) — or the button does not call requestPermission.
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)
The camera calls onBarcodeScanned for every frame that shows the code.
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: …”
The words differ from the screen (a getBy query needs the whole text), or the element appears a moment later.
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”
toHaveBeenCalledWith was used on a real function: the package was not replaced by a mock.
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 …”
The test runs the code but does not check the part that broke.
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: …”
Maestro matches the whole text of an element, and the words or letters differ.
Use the exact text from the screen, or tap by id: - tapOn: { id: "sample-scan" }.
app.json or eas.json “is not valid JSON”
A missing comma or quote, or a comma after the last item.
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)
iPhones turn haptics off while the camera is active, in Low Power Mode, and when System Haptics is off.
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…















