-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
JSIModuleMock.kt
232 lines (196 loc) · 7.78 KB
/
JSIModuleMock.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
@file:OptIn(ExperimentalCoroutinesApi::class)
package expo.modules.kotlin.jni
import android.view.View
import com.facebook.react.bridge.CatalystInstance
import com.facebook.react.bridge.ReactContext
import com.facebook.react.uimanager.UIBlock
import com.facebook.react.uimanager.UIManagerModule
import com.google.common.truth.Truth
import expo.modules.kotlin.AppContext
import expo.modules.kotlin.ModuleHolder
import expo.modules.kotlin.ModuleRegistry
import expo.modules.kotlin.defaultmodules.CoreModule
import expo.modules.kotlin.exception.CodedException
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
import expo.modules.kotlin.modules.ModuleDefinitionBuilder
import expo.modules.kotlin.sharedobjects.ClassRegistry
import expo.modules.kotlin.sharedobjects.SharedObjectRegistry
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.TestScope
import java.lang.ref.WeakReference
internal fun defaultAppContextMock(
jniDeallocator: JNIDeallocator = JNIDeallocator(shouldCreateDestructorThread = false)
): AppContext {
val appContextMock = mockk<AppContext>()
val coreModule = run {
val module = CoreModule()
module._appContext = appContextMock
ModuleHolder(module)
}
every { appContextMock.coreModule } answers { coreModule }
every { appContextMock.classRegistry } answers { ClassRegistry() }
every { appContextMock.jniDeallocator } answers { jniDeallocator }
every { appContextMock.findView<View>(capture(slot())) } answers { mockk() }
return appContextMock
}
/**
* Sets up a test jsi environment with provided modules.
*/
@OptIn(ExperimentalCoroutinesApi::class)
internal inline fun withJSIInterop(
vararg modules: Module,
block: JSIInteropModuleRegistry.(methodQueue: TestScope) -> Unit,
afterCleanup: (deallocator: JNIDeallocator) -> Unit
) {
val jniDeallocator = JNIDeallocator(
shouldCreateDestructorThread = false
)
val appContextMock = defaultAppContextMock(jniDeallocator)
val methodQueue = TestScope()
val uiManagerModuleMock = mockk<UIManagerModule>()
val slot = slot<UIBlock>()
every { uiManagerModuleMock.addUIBlock(capture(slot)) } answers {
methodQueue.launch {
slot.captured.execute(mockk())
}
}
val catalystInstanceMock = mockk<CatalystInstance>()
every { catalystInstanceMock.getNativeModule(UIManagerModule::class.java) } answers { uiManagerModuleMock }
val reactContextMock = mockk<ReactContext>()
every { reactContextMock.isBridgeless } answers { false }
every { reactContextMock.hasCatalystInstance() } answers { true }
every { reactContextMock.hasActiveReactInstance() } answers { true }
every { reactContextMock.catalystInstance } answers { catalystInstanceMock }
every { appContextMock.modulesQueue } answers { methodQueue }
every { appContextMock.mainQueue } answers { methodQueue }
every { appContextMock.backgroundCoroutineScope } answers { methodQueue }
every { appContextMock.reactContext } answers { reactContextMock }
every { appContextMock.assertMainThread() } answers { }
val functionSlot = slot<() -> Unit>()
every { appContextMock.dispatchOnMainUsingUIManager(capture(functionSlot)) } answers {
functionSlot.captured.invoke()
}
val registry = ModuleRegistry(WeakReference(appContextMock)).apply {
modules.forEach {
register(it)
}
}
val sharedObjectRegistry = SharedObjectRegistry(appContextMock)
every { appContextMock.registry } answers { registry }
every { appContextMock.sharedObjectRegistry } answers { sharedObjectRegistry }
val jsiIterop = JSIInteropModuleRegistry()
every { appContextMock.jsiInterop } answers { jsiIterop }
jsiIterop.installJSIForTests(appContextMock, jniDeallocator)
block(jsiIterop, methodQueue)
jniDeallocator.deallocate()
jsiIterop.deallocate()
afterCleanup(jniDeallocator)
}
open class TestContext(
val jsiInterop: JSIInteropModuleRegistry,
val methodQueue: TestScope
) {
fun global() = jsiInterop.global()
fun evaluateScript(script: String) = jsiInterop.evaluateScript(script)
fun waitForAsyncFunction(jsCode: String) = jsiInterop.waitForAsyncFunction(methodQueue, jsCode)
}
class SingleTestContext(
moduleName: String,
jsiInterop: JSIInteropModuleRegistry,
methodQueue: TestScope
) : TestContext(jsiInterop, methodQueue) {
val moduleRef = "expo.modules.$moduleName"
fun property(propertyName: String) =
jsiInterop.evaluateScript("$moduleRef.$propertyName")
fun property(propertyName: String, newValue: String) {
jsiInterop.evaluateScript("$moduleRef.$propertyName = $newValue")
}
fun call(functionName: String, args: String = "") = jsiInterop.evaluateScript(
"$moduleRef.$functionName($args)"
)
fun callClass(className: String, functionName: String? = null, args: String = ""): JavaScriptValue {
if (functionName == null) {
return jsiInterop.evaluateScript("new $moduleRef.$className()")
}
return jsiInterop.evaluateScript("(new $moduleRef.$className()).$functionName($args)")
}
fun classProperty(className: String, propertyName: String) =
jsiInterop.evaluateScript("(new $moduleRef.$className()).$propertyName")
fun callAsync(functionName: String, args: String = "") = jsiInterop.waitForAsyncFunction(
methodQueue,
"$moduleRef.$functionName($args)"
)
fun callClassAsync(className: String, functionName: String? = null, args: String = ""): JavaScriptValue {
if (functionName == null) {
return jsiInterop.evaluateScript("new $moduleRef.$className()")
}
return jsiInterop.waitForAsyncFunction(methodQueue, "(new $moduleRef.$className()).$functionName($args)")
}
fun callViewAsync(viewName: String, functionName: String, args: String = ""): JavaScriptValue {
return jsiInterop.waitForAsyncFunction(methodQueue, "$moduleRef.$viewName.$functionName($args)")
}
}
internal inline fun withJSIInterop(
vararg modules: Module,
block: JSIInteropModuleRegistry.(methodQueue: TestScope) -> Unit
) = withJSIInterop(*modules, block = block, afterCleanup = {})
internal inline fun withSingleModule(
crossinline definition: ModuleDefinitionBuilder.() -> Unit = {},
block: SingleTestContext.() -> Unit
) {
var moduleName = "TestModule"
withJSIInterop(
object : Module() {
override fun definition() = ModuleDefinition {
Name(moduleName)
definition()
name?.let {
moduleName = it
}
}
},
block = { methodQueue ->
val testContext = SingleTestContext(moduleName, this, methodQueue)
block.invoke(testContext)
}
)
}
/**
* A syntax sugar that creates a new module from the definition block.
*/
internal inline fun inlineModule(
crossinline block: ModuleDefinitionBuilder.() -> Unit
) = object : Module() {
override fun definition() = ModuleDefinition { block.invoke(this) }
}
@Suppress("NOTHING_TO_INLINE")
@OptIn(ExperimentalCoroutinesApi::class)
@Throws(PromiseException::class)
internal inline fun JSIInteropModuleRegistry.waitForAsyncFunction(
methodQueue: TestScope,
jsCode: String
): JavaScriptValue {
evaluateScript(
"""
$jsCode.then(r => global.promiseResult = r).catch(e => global.promiseError = e)
""".trimIndent()
)
methodQueue.testScheduler.advanceUntilIdle()
drainJSEventLoop()
if (global().hasProperty("promiseError")) {
val jsError = global().getProperty("promiseError").getObject()
val code = jsError.getProperty("code").getString()
val errorMessage = jsError.getProperty("message").getString()
throw PromiseException(code, errorMessage)
}
Truth
.assertWithMessage("Promise wasn't resolved")
.that(global().hasProperty("promiseResult")).isTrue()
return global().getProperty("promiseResult")
}
class PromiseException(code: String, message: String) : CodedException(code, message, null)