expo-secure-store的setItemAsync与getItemAsync在Jest中失效
关于expo-secure-store与Jest的测试问题
我使用expo-secure-store在用户登录时存储access_token,该功能在真机/模拟器上运行正常,但在Jest测试中完全失效——获取到的token始终为undefined,不过函数本身可以正常调用。
测试代码
test('Test SecureStore wrt Jest', async () => { try { await SecureStore.setItemAsync(TOKEN, 'randomToken'); const token = await SecureStore.getItemAsync(TOKEN); console.log(token); expect(token).toBeDefined(); expect(token).toBe(randomToken); } catch (error) { console.log(error); throw error; } }
项目package.json配置
{ "dependencies": { "@testing-library/jest-dom": "^5.16.4", "@testing-library/react-native": "10.1.1", "expo": "^44.0.0", "jest": "28.1.2", "jest-expo": "^45.0.1", "react": "17.0.1", "react-native": "0.64.3", "ts-jest": "^28.0.0-next.3" }, "devDependencies": { "@types/jest": "^28.1.5", "@types/react-test-renderer": "^18.0.0", "jest-environment-jsdom": "^28.1.2", "react-test-renderer": "17.0.1", } }
当前使用的mock文件内容
jest.mock('expo-secure-store', () => { const realConstants = jest.requireActual('expo-constants').default const mockConstants = Object.create(realConstants) const realExpoSecureStore = jest.requireActual( 'expo-secure-store/src/SecureStore' ) const realExpoModulesCore = jest.requireActual( 'expo-modules-core/src/NativeModulesProxy' ) return { ...realConstants, ...realExpoSecureStore, ...realExpoModulesCore, mockConstants, NativeModulesProxy: { ExpoSecureStore: { setValueWithKeyAsync: jest.fn(), getValueWithKeyAsync: jest.fn(), }, }, SecureStore: { setItemAsync: jest.fn(), getItemAsync: jest.fn(), }, } })
内容的提问来源于stack exchange,提问作者Supriya Kalghatgi
相关产品推荐
相关产品推荐

