expo-sqlite-mock 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024-present, Zhu Feng
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,6 @@
1
+ # expo-sqlite-mock
2
+
3
+ [![License: MIT](https://img.shields.io/npm/l/expo-sqlite-mock.svg)](https://github.com/zfben/expo-sqlite-mock/blob/main/packages/faasjs/jest/LICENSE)
4
+ [![NPM Version](https://img.shields.io/npm/v/expo-sqlite-mock.svg)](https://www.npmjs.com/package/expo-sqlite-mock)
5
+
6
+ Use expo-sqlite with jest.
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "expo-sqlite-mock",
3
+ "version": "0.0.1",
4
+ "scripts": {
5
+ "test": "jest"
6
+ },
7
+ "jest": {
8
+ "preset": "jest-expo",
9
+ "testRegex": "/*\\.test\\.tsx?$"
10
+ },
11
+ "files": [
12
+ "src"
13
+ ],
14
+ "peerDependencies": {
15
+ "better-sqlite3": "*",
16
+ "jest": "*",
17
+ "expo-sqlite": "*"
18
+ },
19
+ "devDependencies": {
20
+ "typescript": "*",
21
+ "@biomejs/biome": "*",
22
+ "expo-sqlite": "*",
23
+ "better-sqlite3": "*",
24
+ "@types/better-sqlite3": "*",
25
+ "@types/react": "*",
26
+ "react": "*",
27
+ "react-test-renderer": "18.2.0",
28
+ "@faasjs/jest": "*",
29
+ "@testing-library/react-native": "*",
30
+ "jest-expo": "*"
31
+ }
32
+ }
@@ -0,0 +1,235 @@
1
+ import assert from 'node:assert'
2
+ import sqlite3 from 'better-sqlite3'
3
+
4
+ import type { SQLiteOpenOptions } from 'expo-sqlite/src/NativeDatabase'
5
+ import type {
6
+ SQLiteBindBlobParams,
7
+ SQLiteBindParams,
8
+ SQLiteBindPrimitiveParams,
9
+ SQLiteColumnNames,
10
+ SQLiteColumnValues,
11
+ SQLiteRunResult,
12
+ } from 'expo-sqlite/src/NativeStatement'
13
+
14
+ export const mockedExpoSqliteNext = {
15
+ deleteDatabaseAsync: jest.fn(),
16
+
17
+ NativeDatabase: jest
18
+ .fn()
19
+ .mockImplementation(
20
+ (databaseName: string, options?: SQLiteOpenOptions, serializedData?: Uint8Array) =>
21
+ new NativeDatabase(databaseName, options, serializedData)
22
+ ),
23
+
24
+ NativeStatement: jest.fn().mockImplementation(() => new NativeStatement()),
25
+ }
26
+
27
+ //#region async sqlite3
28
+
29
+ /**
30
+ * A sqlite3.Database wrapper with async methods and conforming to the NativeDatabase interface.
31
+ */
32
+ class NativeDatabase {
33
+ private readonly sqlite3Db: sqlite3.Database
34
+
35
+ constructor(databaseName: string, options?: SQLiteOpenOptions, serializedData?: Uint8Array) {
36
+ if (serializedData != null) {
37
+ this.sqlite3Db = new sqlite3(Buffer.from(serializedData))
38
+ } else {
39
+ this.sqlite3Db = new sqlite3(':memory:')
40
+ }
41
+ }
42
+
43
+ //#region Asynchronous API
44
+
45
+ initAsync = jest.fn().mockResolvedValue(null)
46
+ isInTransactionAsync = jest.fn().mockImplementation(async () => {
47
+ return this.sqlite3Db.inTransaction
48
+ })
49
+ closeAsync = jest.fn().mockImplementation(async () => {
50
+ return this.sqlite3Db.close()
51
+ })
52
+ execAsync = jest.fn().mockImplementation(async (source: string) => {
53
+ return this.sqlite3Db.exec(source)
54
+ })
55
+ serializeAsync = jest.fn().mockImplementation(async (databaseName: string) => {
56
+ return this.sqlite3Db.serialize({ attached: databaseName })
57
+ })
58
+ prepareAsync = jest.fn().mockImplementation(async (nativeStatement: NativeStatement, source: string) => {
59
+ nativeStatement.sqlite3Stmt = this.sqlite3Db.prepare(source)
60
+ })
61
+
62
+ //#endregion
63
+
64
+ //#region Synchronous API
65
+
66
+ initSync = jest.fn()
67
+ isInTransactionSync = jest.fn().mockImplementation(() => this.sqlite3Db.inTransaction)
68
+ closeSync = jest.fn().mockImplementation(() => this.sqlite3Db.close())
69
+ execSync = jest.fn().mockImplementation((source: string) => this.sqlite3Db.exec(source))
70
+ serializeSync = jest.fn().mockImplementation((databaseName: string) => {
71
+ return this.sqlite3Db.serialize({ attached: databaseName })
72
+ })
73
+ prepareSync = jest.fn().mockImplementation((nativeStatement: NativeStatement, source: string) => {
74
+ nativeStatement.sqlite3Stmt = this.sqlite3Db.prepare(source)
75
+ })
76
+
77
+ //#endregion
78
+ }
79
+
80
+ /**
81
+ * A sqlite3.Statement wrapper with async methods and conforming to the NativeStatement interface.
82
+ */
83
+ class NativeStatement {
84
+ public sqlite3Stmt: sqlite3.Statement | null = null
85
+ private iterator: ReturnType<sqlite3.Statement['iterate']> | null = null
86
+
87
+ //#region Asynchronous API
88
+
89
+ public runAsync = jest
90
+ .fn()
91
+ .mockImplementation(
92
+ (
93
+ database: NativeDatabase,
94
+ bindParams: SQLiteBindPrimitiveParams,
95
+ bindBlobParams: SQLiteBindBlobParams,
96
+ shouldPassAsArray: boolean
97
+ ): Promise<SQLiteRunResult & { firstRowValues: SQLiteColumnValues }> =>
98
+ Promise.resolve(this._run(normalizeSQLite3Args(bindParams, bindBlobParams, shouldPassAsArray)))
99
+ )
100
+ public stepAsync = jest.fn().mockImplementation((database: NativeDatabase): Promise<any> => {
101
+ assert(this.sqlite3Stmt)
102
+ if (this.iterator == null) {
103
+ this.iterator = this.sqlite3Stmt.iterate()
104
+ // Since the first row is retrieved by `_run()`, we need to skip the first row here.
105
+ this.iterator.next()
106
+ }
107
+ const result = this.iterator.next()
108
+ const columnValues = result.done === false ? Object.values(result.value as Record<string, any>) : null
109
+ return Promise.resolve(columnValues)
110
+ })
111
+ public getAllAsync = jest.fn().mockImplementation((database: NativeDatabase) => Promise.resolve(this._allValues()))
112
+ public getColumnNamesAsync = jest.fn().mockImplementation(async (database: NativeDatabase) => {
113
+ assert(this.sqlite3Stmt)
114
+ return this.sqlite3Stmt.columns().map(column => column.name)
115
+ })
116
+ public resetAsync = jest.fn().mockImplementation(async (database: NativeDatabase) => {
117
+ this._reset()
118
+ })
119
+ public finalizeAsync = jest.fn().mockImplementation(async (database: NativeDatabase) => {
120
+ this._finalize()
121
+ })
122
+
123
+ //#endregion
124
+
125
+ //#region Synchronous API
126
+
127
+ public runSync = jest
128
+ .fn()
129
+ .mockImplementation(
130
+ (
131
+ database: NativeDatabase,
132
+ bindParams: SQLiteBindPrimitiveParams,
133
+ bindBlobParams: SQLiteBindBlobParams,
134
+ shouldPassAsArray: boolean
135
+ ): SQLiteRunResult & { firstRowValues: SQLiteColumnValues } =>
136
+ this._run(normalizeSQLite3Args(bindParams, bindBlobParams, shouldPassAsArray))
137
+ )
138
+ public stepSync = jest.fn().mockImplementation((database: NativeDatabase): any => {
139
+ assert(this.sqlite3Stmt)
140
+ if (this.iterator == null) {
141
+ this.iterator = this.sqlite3Stmt.iterate()
142
+ // Since the first row is retrieved by `_run()`, we need to skip the first row here.
143
+ this.iterator.next()
144
+ }
145
+
146
+ const result = this.iterator.next()
147
+ const columnValues = result.done === false ? Object.values(result.value as Record<string, any>) : null
148
+ return columnValues
149
+ })
150
+ public getAllSync = jest.fn().mockImplementation((database: NativeDatabase) => this._allValues())
151
+ public getColumnNamesSync = jest.fn().mockImplementation((database: NativeDatabase) => {
152
+ assert(this.sqlite3Stmt)
153
+ return this.sqlite3Stmt.columns().map(column => column.name)
154
+ })
155
+ public resetSync = jest.fn().mockImplementation((database: NativeDatabase) => {
156
+ this._reset()
157
+ })
158
+ public finalizeSync = jest.fn().mockImplementation((database: NativeDatabase) => {
159
+ this._finalize()
160
+ })
161
+
162
+ //#endregion
163
+
164
+ private _run = (...params: any[]): SQLiteRunResult & { firstRowValues: SQLiteColumnValues } => {
165
+ assert(this.sqlite3Stmt)
166
+ this.sqlite3Stmt.bind(...params)
167
+ const result = this.sqlite3Stmt.run()
168
+
169
+ // better-sqlite3 does not support run() returning the first row, use get() instead.
170
+ let firstRow: any
171
+ try {
172
+ firstRow = this.sqlite3Stmt.get()
173
+ } catch {
174
+ // better-sqlite3 may throw `TypeError: This statement does not return data. Use run() instead`
175
+ firstRow = null
176
+ }
177
+ return {
178
+ lastInsertRowId: Number(result.lastInsertRowid),
179
+ changes: result.changes,
180
+ firstRowValues: firstRow ? Object.values(firstRow) : [],
181
+ }
182
+ }
183
+
184
+ private _allValues = (): SQLiteColumnNames[] => {
185
+ assert(this.sqlite3Stmt)
186
+ const sqlite3Stmt = this.sqlite3Stmt as any
187
+ // Since the first row is retrieved by `_run()`, we need to skip the first row here.
188
+ return sqlite3Stmt
189
+ .all()
190
+ .slice(1)
191
+ .map((row: any) => Object.values(row))
192
+ }
193
+
194
+ private _reset = () => {
195
+ assert(this.sqlite3Stmt)
196
+ this.iterator?.return?.()
197
+ this.iterator = this.sqlite3Stmt.iterate()
198
+ }
199
+
200
+ private _finalize = () => {
201
+ this.iterator?.return?.()
202
+ this.iterator = null
203
+ }
204
+ }
205
+
206
+ //#endregion
207
+
208
+ function normalizeSQLite3Args(
209
+ bindParams: SQLiteBindPrimitiveParams,
210
+ bindBlobParams: SQLiteBindBlobParams,
211
+ shouldPassAsArray: boolean
212
+ ): SQLiteBindParams {
213
+ if (shouldPassAsArray) {
214
+ const result: SQLiteBindParams = []
215
+ for (const [key, value] of Object.entries(bindParams)) {
216
+ result[Number(key)] = value
217
+ }
218
+ for (const [key, value] of Object.entries(bindBlobParams)) {
219
+ result[Number(key)] = value
220
+ }
221
+ return result
222
+ }
223
+
224
+ const replaceRegexp = /^[:@$]/
225
+ const result: SQLiteBindParams = {}
226
+ for (const [key, value] of Object.entries(bindParams)) {
227
+ const normalizedKey = key.replace(replaceRegexp, '')
228
+ result[normalizedKey] = value
229
+ }
230
+ for (const [key, value] of Object.entries(bindBlobParams)) {
231
+ const normalizedKey = key.replace(replaceRegexp, '')
232
+ result[normalizedKey] = value
233
+ }
234
+ return result
235
+ }
@@ -0,0 +1,32 @@
1
+ import { mockedExpoSqliteNext } from '../ExpoSQLiteNext'
2
+ import { Text } from 'react-native'
3
+ import { SQLiteProvider, useSQLiteContext } from 'expo-sqlite'
4
+ import { render, screen } from '@testing-library/react-native'
5
+ import { useEffect, useState } from 'react'
6
+
7
+ jest.mock(`${__dirname}/../../node_modules/expo-sqlite/build/ExpoSQLiteNext`, () => mockedExpoSqliteNext)
8
+
9
+ it('SQLiteProvider', async () => {
10
+ function Test() {
11
+ const db = useSQLiteContext()
12
+ const [version, setVersion] = useState('')
13
+
14
+ useEffect(() => {
15
+ setVersion(db.getFirstSync<{ 'sqlite_version()': string }>('SELECT sqlite_version()')['sqlite_version()'])
16
+ }, [])
17
+
18
+ return <Text>{version}</Text>
19
+ }
20
+
21
+ function App() {
22
+ return (
23
+ <SQLiteProvider databaseName='test.db'>
24
+ <Test />
25
+ </SQLiteProvider>
26
+ )
27
+ }
28
+
29
+ render(<App />)
30
+
31
+ expect(await screen.findByText(/[0-9]+.[0-9]+.[0-9]+/)).toBeTruthy()
32
+ })
package/src/setup.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { mockedExpoSqliteNext } from './ExpoSQLiteNext'
2
+
3
+ jest.mock(`${__dirname}/../../expo-sqlite/build/ExpoSQLiteNext`, () => mockedExpoSqliteNext)