Test SQLite with jest

Hello, I want to test SQLite module in expo.

But, SQLite is related to native SDK, and jest cannot run SQLite module.

Is there any mock or fake can replace SQLite in test code?

Assuming you want to test your custom code that uses the SQLite module (and not the SQLite module itself, which presumably already has its own unit tests), you should inject the SQLite module as a dependency of your class that uses it, so you can provide an alternative implementation in your Jest tests.

If you Google “jest mock dependencies”, you’ll see a lot of ways to do this. If you ask me, the most straightforward way is old-fashioned dependency injection, which works in virtually any language. You write your own class that takes SQLite as a constructor parameter. Then, in your class code, you reference that parameter (probably saved as a member variable) instead of the SQLite library. In your actual app, you’ll pass Expo.SQLite as the parameter, and in your tests, you’ll pass a mock, which will be something like { executeSql: jest.mock(() => Promise.resolve(/* put something here*/)) }. What’s nice is, in Jest, if a particular test doesn’t use a SQLite function, you don’t have to mock it.

1 Like

Thanks for the reply!

I know that I can test by test double(fake).

But I want to do a learning test.

Which means I want to see the exact instance when I query something(insert, update).

I google some test code about SQLite in expo but I cannot find.

Thanks for your reply again!

If you want to play with the SQLite API to learn it, you can do that in an Expo app running on a device or simulator. It will not work with Jest, since Jest isn’t running on a phone, and therefore doesn’t have access to SQLite. You can find information about Expo’s SQLite implementation here: SQLite - Expo Documentation

Thank you for your help.

I think I have to make SQLite mock later.

Thank you very much again!

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.