Skip to content

Commit

Permalink
Splitting Profile in separate components for AX snapshot testing
Browse files Browse the repository at this point in the history
A `SnapshotTest` native module was created to register every component from the JavaScript thread instead of having to modify Swift files every time
  • Loading branch information
DimitarNestorov committed Apr 19, 2023
1 parent c994a7d commit d9f7b7c
Show file tree
Hide file tree
Showing 10 changed files with 153 additions and 50 deletions.
10 changes: 9 additions & 1 deletion ios/AccessibilitySnapshotExample.xcodeproj/project.pbxproj
Expand Up @@ -13,6 +13,8 @@
13B07FC11A68108700A75B9A /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; };
4371710C29EFFF54006B6B15 /* AccessibilitySnapshot in Frameworks */ = {isa = PBXBuildFile; productRef = 4371710B29EFFF54006B6B15 /* AccessibilitySnapshot */; };
4371710E29EFFF88006B6B15 /* SnapshotTesting in Frameworks */ = {isa = PBXBuildFile; productRef = 4371710D29EFFF88006B6B15 /* SnapshotTesting */; };
4371711529F03706006B6B15 /* SnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4371711429F03706006B6B15 /* SnapshotTests.swift */; };
4371711829F03E2E006B6B15 /* SnapshotTestsBridge.m in Sources */ = {isa = PBXBuildFile; fileRef = 4371711729F03E2E006B6B15 /* SnapshotTestsBridge.m */; };
43EE060829EFF89500D2757D /* AccessibilitySnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43EE060729EFF89500D2757D /* AccessibilitySnapshotTests.swift */; };
7699B88040F8A987B510C191 /* libPods-AccessibilitySnapshotExample-AccessibilitySnapshotExampleTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 19F6CBCC0A4E27FBF8BF4A61 /* libPods-AccessibilitySnapshotExample-AccessibilitySnapshotExampleTests.a */; };
81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */; };
Expand All @@ -39,6 +41,8 @@
13B07FB71A68108700A75B9A /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = AccessibilitySnapshotExample/main.m; sourceTree = "<group>"; };
19F6CBCC0A4E27FBF8BF4A61 /* libPods-AccessibilitySnapshotExample-AccessibilitySnapshotExampleTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-AccessibilitySnapshotExample-AccessibilitySnapshotExampleTests.a"; sourceTree = BUILT_PRODUCTS_DIR; };
3B4392A12AC88292D35C810B /* Pods-AccessibilitySnapshotExample.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AccessibilitySnapshotExample.debug.xcconfig"; path = "Target Support Files/Pods-AccessibilitySnapshotExample/Pods-AccessibilitySnapshotExample.debug.xcconfig"; sourceTree = "<group>"; };
4371711429F03706006B6B15 /* SnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SnapshotTests.swift; sourceTree = "<group>"; };
4371711729F03E2E006B6B15 /* SnapshotTestsBridge.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SnapshotTestsBridge.m; sourceTree = "<group>"; };
43EE060729EFF89500D2757D /* AccessibilitySnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccessibilitySnapshotTests.swift; sourceTree = "<group>"; };
5709B34CF0A7D63546082F79 /* Pods-AccessibilitySnapshotExample.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AccessibilitySnapshotExample.release.xcconfig"; path = "Target Support Files/Pods-AccessibilitySnapshotExample/Pods-AccessibilitySnapshotExample.release.xcconfig"; sourceTree = "<group>"; };
5B7EB9410499542E8C5724F5 /* Pods-AccessibilitySnapshotExample-AccessibilitySnapshotExampleTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AccessibilitySnapshotExample-AccessibilitySnapshotExampleTests.debug.xcconfig"; path = "Target Support Files/Pods-AccessibilitySnapshotExample-AccessibilitySnapshotExampleTests/Pods-AccessibilitySnapshotExample-AccessibilitySnapshotExampleTests.debug.xcconfig"; sourceTree = "<group>"; };
Expand Down Expand Up @@ -74,6 +78,8 @@
isa = PBXGroup;
children = (
43EE060729EFF89500D2757D /* AccessibilitySnapshotTests.swift */,
4371711429F03706006B6B15 /* SnapshotTests.swift */,
4371711729F03E2E006B6B15 /* SnapshotTestsBridge.m */,
00E356F01AD99517003FC87E /* Supporting Files */,
);
path = AccessibilitySnapshotExampleTests;
Expand Down Expand Up @@ -216,7 +222,7 @@
TargetAttributes = {
00E356ED1AD99517003FC87E = {
CreatedOnToolsVersion = 6.2;
LastSwiftMigration = 1420;
LastSwiftMigration = 1430;
TestTargetID = 13B07F861A680F5B00A75B9A;
};
13B07F861A680F5B00A75B9A = {
Expand Down Expand Up @@ -422,6 +428,8 @@
buildActionMask = 2147483647;
files = (
43EE060829EFF89500D2757D /* AccessibilitySnapshotTests.swift in Sources */,
4371711829F03E2E006B6B15 /* SnapshotTestsBridge.m in Sources */,
4371711529F03706006B6B15 /* SnapshotTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
Expand Up @@ -4,40 +4,66 @@ import SnapshotTesting
import XCTest

class AccessibilitySnapshotTests : XCTestCase {
let bridge = RCTBridge(bundleURL: ProcessInfo.processInfo.environment["USE_LOCAL_BUNDLE"] == nil
? RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
: Bundle.main.url(forResource: "main", withExtension: "jsbundle")!,
moduleProvider: nil)!

func testAccessibilitySnapshot() {
let expectation = expectation(description: "Wait for content to appear")
let observer = Observer(expectation)
let profileView = RCTRootView(frame: .init(x: 0, y: 0, width: 300, height: 700),
bridge: bridge,
moduleName: "ProfileTest",
initialProperties: nil)
NotificationCenter.default.addObserver(observer,
selector: #selector(observer.handler),
name: NSNotification.Name("RCTContentDidAppearNotification"),
object: profileView)
defer {
NotificationCenter.default.removeObserver(observer)
}
func testAccessibilitySnapshot() throws {
let bridgeDelegate = BridgeDelegate()

let expectationForJavaScriptDidLoadNotification = expectation(description: "Wait for JavaScript to load")
let observerForJavaScriptDidLoadNotification = Observer(expectationForJavaScriptDidLoadNotification)
let bridge = RCTBridge(delegate: bridgeDelegate, launchOptions: nil)!
NotificationCenter.default.addObserver(observerForJavaScriptDidLoadNotification,
selector: #selector(observerForJavaScriptDidLoadNotification.handler),
name: NSNotification.Name("RCTJavaScriptDidLoadNotification"),
object: bridge)
defer { NotificationCenter.default.removeObserver(observerForJavaScriptDidLoadNotification) }

_ = XCTWaiter.wait(for: [expectation], timeout: 5.0)
_ = XCTWaiter.wait(for: [expectationForJavaScriptDidLoadNotification], timeout: 5.0)

assertSnapshot(matching: profileView, as: .accessibilityImage(perceptualPrecision: 0.995))
let items = try XCTUnwrap(bridgeDelegate.snapshotTests.items, "Check logs if the same name was already registered")

XCTAssertFalse(items.isEmpty)

for item in items {
let expectation = expectation(description: "Wait for content to appear")
let observer = Observer(expectation)
let profileView = RCTRootView(frame: .init(x: 0, y: 0, width: 300, height: 700),
bridge: bridge,
moduleName: item,
initialProperties: nil)
NotificationCenter.default.addObserver(observer,
selector: #selector(observer.handler),
name: NSNotification.Name("RCTContentDidAppearNotification"),
object: profileView)
defer { NotificationCenter.default.removeObserver(observer) }

_ = XCTWaiter.wait(for: [expectation], timeout: 5.0)

assertSnapshot(matching: profileView, as: .accessibilityImage(perceptualPrecision: 0.995), named: item, testName: "accessibility")
}
}
}

class Observer {
let expectation: XCTestExpectation

init(_ expectation: XCTestExpectation) {
self.expectation = expectation
private class Observer {
let expectation: XCTestExpectation

init(_ expectation: XCTestExpectation) {
self.expectation = expectation
}

@objc func handler(_ notification: NSNotification) {
expectation.fulfill()
}
}

@objc func handler(_ notification: NSNotification) {
expectation.fulfill()

private class BridgeDelegate: NSObject, RCTBridgeDelegate {
public let snapshotTests = SnapshotTests()

func sourceURL(for bridge: RCTBridge!) -> URL! {
ProcessInfo.processInfo.environment["USE_LOCAL_BUNDLE"] == nil
? RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
: Bundle.main.url(forResource: "main", withExtension: "jsbundle")!
}

func extraModules(for bridge: RCTBridge!) -> [RCTBridgeModule]! {
[snapshotTests]
}
}
}
30 changes: 30 additions & 0 deletions ios/AccessibilitySnapshotExampleTests/SnapshotTests.swift
@@ -0,0 +1,30 @@
import Foundation
import XCTest
import React

@objc(SnapshotTests)
class SnapshotTests: NSObject, RCTBridgeModule {
static func moduleName() -> String! {
"SnapshotTests"
}

var items: [String]? = []

@objc(registerName:)
func register(name: String) -> NSNumber? {
guard let items = items else {
return nil
}

if items.contains(name) {
self.items = nil
NSException.raise(.init(rawValue: "Name already registered"),
format: "%@ already registered",
arguments: getVaList([name]))
print("\(name) already registered")
}

self.items!.append(name)
return NSNumber(booleanLiteral: true)
}
}
7 changes: 7 additions & 0 deletions ios/AccessibilitySnapshotExampleTests/SnapshotTestsBridge.m
@@ -0,0 +1,7 @@
#import <React/RCTBridgeModule.h>

@interface RCT_EXTERN_MODULE(SnapshotTests, NSObject)

RCT_EXTERN__BLOCKING_SYNCHRONOUS_METHOD(registerName:(NSString *)name)

@end
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
53 changes: 34 additions & 19 deletions src/Profile.tsx
@@ -1,23 +1,24 @@
import React from 'react';
import {
AppRegistry,
Image,
StyleSheet,
Text,
TouchableOpacity,
View,
} from 'react-native';
import {Image, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import registerAccessibilitySnapshotNode from './utils/registerAccessibilitySnapshotNode';

const tomProfilePicture =
'https://images.unsplash.com/photo-1569591159212-b02ea8a9f239?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MzN8fGNhdHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=900&q=60';

export default function Profile({
picture = tomProfilePicture,
}: {
picture: string;
}) {
export default function Profile({picture}: {picture?: string}) {
return (
<View style={styles.container}>
<ProfilePicture picture={picture} />
<Text style={styles.text}>Tom</Text>
<Stats />
<Buttons />
</View>
);
}

function ProfilePicture({picture = tomProfilePicture}: {picture?: string}) {
return (
<>
<TouchableOpacity
aria-label="Profile picture"
accessibilityHint="Double tap to edit"
Expand All @@ -31,8 +32,13 @@ export default function Profile({
</Text>
</View>
</TouchableOpacity>
<Text style={styles.text}>Tom</Text>
</>
);
}

function Stats() {
return (
<>
<View style={styles.stats}>
<View style={styles.stat} accessible aria-label="Games: 15">
<Text style={styles.statNumber} maxFontSizeMultiplier={3}>
Expand All @@ -55,7 +61,13 @@ export default function Profile({
<Text maxFontSizeMultiplier={2.7}>Points</Text>
</View>
</View>
</>
);
}

function Buttons() {
return (
<>
<View style={styles.buttons}>
<TouchableOpacity
style={styles.button}
Expand All @@ -70,10 +82,9 @@ export default function Profile({
<Text style={styles.buttonText}>Delete Profile</Text>
</TouchableOpacity>
</View>
</View>
</>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
Expand Down Expand Up @@ -148,7 +159,11 @@ const styles = StyleSheet.create({
});

if (__DEV__) {
AppRegistry.registerComponent('ProfileTest', () => () => (
<Profile picture="" />
));
registerAccessibilitySnapshotNode('ProfileTest', <Profile picture="" />);
registerAccessibilitySnapshotNode(
'ProfilePictureTest',
<ProfilePicture picture="" />,
);
registerAccessibilitySnapshotNode('ProfileStatsTest', <Stats />);
registerAccessibilitySnapshotNode('ProfileButtonsTest', <Buttons />);
}
17 changes: 17 additions & 0 deletions src/utils/registerAccessibilitySnapshotNode.tsx
@@ -0,0 +1,17 @@
import {AppRegistry, NativeModules} from 'react-native';

export default function registerAccessibilitySnapshotNode(
name: string,
node: JSX.Element,
) {
AppRegistry.registerComponent(name, () => () => node);
const {SnapshotTests} = NativeModules;
if (!SnapshotTests) {
return;
}

const result = SnapshotTests.registerName(name);
if (!result) {
throw new Error(`Couldn't register ${name}`);
}
}

0 comments on commit d9f7b7c

Please sign in to comment.