• Home
  • Insight
  • Blog
  • Business
  • Entertainment
  • Health
  • Politics
  • Shop
    • Gift Shop
    • Value Shop
    • Store
    • Bargain Shop
    • Discount
  • Sports
  • Tech
  • Travel
  • USA
  • Video
  • World
    • Asia
    • Africa
    • South America
    • North America
    • Europe
    • Oceania
Monday, November 16, 2026
No Result
View All Result
Subscribe Now
  • Home
  • Insight
  • Blog
  • Business
  • Entertainment
  • Health
  • Politics
  • Shop
    • Gift Shop
    • Value Shop
    • Store
    • Bargain Shop
    • Discount
  • Sports
  • Tech
  • Travel
  • USA
    Stranded in Conflict: Palestinians Navigate the Tenuous Balance of War and Peace Amid Ceasefire Efforts

    Stranded in Conflict: Palestinians Navigate the Tenuous Balance of War and Peace Amid Ceasefire Efforts

    Trump Administration Revokes Pay Increase for Head Start Educators

    Trump Administration Revokes Pay Increase for Head Start Educators

    Unexpected Triumph: Gay Candidates Achieve Unforeseen Victories in Challenging Races

    Unexpected Triumph: Gay Candidates Achieve Unforeseen Victories in Challenging Races

    Microsoft Outlook Experiences Prolonged Outage Affecting Users Nationwide

    Microsoft Outlook Experiences Prolonged Outage Affecting Users Nationwide

    Gunfire Erupts in D.C.: Authorities Search for Suspect Amid Rising Concerns Over Public Safety

    Gunfire Erupts in D.C.: Authorities Search for Suspect Amid Rising Concerns Over Public Safety

    LAUSD Takes Strong Action Against Hate Speech Following Racial Slur Incidents

    LAUSD Takes Strong Action Against Hate Speech Following Racial Slur Incidents

    Beloved Former Los Angeles Times Columnist Steve Harvey Passes Away at 80

    Beloved Former Los Angeles Times Columnist Steve Harvey Passes Away at 80

    Exploring Diversity: ‘Ten Lives’ Showcases the Varied Economic Journeys of Americans

    Exploring Diversity: ‘Ten Lives’ Showcases the Varied Economic Journeys of Americans

    Philadelphia Eagles Facing Turmoil as Coach Nick Sirianni Addresses Controversy Over Gesture to Fans

    Philadelphia Eagles Facing Turmoil as Coach Nick Sirianni Addresses Controversy Over Gesture to Fans

  • Video
  • World
    • Asia
    • Africa
    • South America
    • North America
    • Europe
    • Oceania
The Insight Post
  • Home
  • Insight
  • Blog
  • Business
  • Entertainment
  • Health
  • Politics
  • Shop
    • Gift Shop
    • Value Shop
    • Store
    • Bargain Shop
    • Discount
  • Sports
  • Tech
  • Travel
  • USA
    Stranded in Conflict: Palestinians Navigate the Tenuous Balance of War and Peace Amid Ceasefire Efforts

    Stranded in Conflict: Palestinians Navigate the Tenuous Balance of War and Peace Amid Ceasefire Efforts

    Trump Administration Revokes Pay Increase for Head Start Educators

    Trump Administration Revokes Pay Increase for Head Start Educators

    Unexpected Triumph: Gay Candidates Achieve Unforeseen Victories in Challenging Races

    Unexpected Triumph: Gay Candidates Achieve Unforeseen Victories in Challenging Races

    Microsoft Outlook Experiences Prolonged Outage Affecting Users Nationwide

    Microsoft Outlook Experiences Prolonged Outage Affecting Users Nationwide

    Gunfire Erupts in D.C.: Authorities Search for Suspect Amid Rising Concerns Over Public Safety

    Gunfire Erupts in D.C.: Authorities Search for Suspect Amid Rising Concerns Over Public Safety

    LAUSD Takes Strong Action Against Hate Speech Following Racial Slur Incidents

    LAUSD Takes Strong Action Against Hate Speech Following Racial Slur Incidents

    Beloved Former Los Angeles Times Columnist Steve Harvey Passes Away at 80

    Beloved Former Los Angeles Times Columnist Steve Harvey Passes Away at 80

    Exploring Diversity: ‘Ten Lives’ Showcases the Varied Economic Journeys of Americans

    Exploring Diversity: ‘Ten Lives’ Showcases the Varied Economic Journeys of Americans

    Philadelphia Eagles Facing Turmoil as Coach Nick Sirianni Addresses Controversy Over Gesture to Fans

    Philadelphia Eagles Facing Turmoil as Coach Nick Sirianni Addresses Controversy Over Gesture to Fans

  • Video
  • World
    • Asia
    • Africa
    • South America
    • North America
    • Europe
    • Oceania
No Result
View All Result
No Result
View All Result
Home Mobile

How to test SQLite for React Native apps using Jest

by Theinsightpost
August 8, 2022
in Mobile
0 0
0
How to test SQLite for React Native apps using Jest


In native Android, it’s common to test SQLite code in isolation. In this article, we will cover how to test SQLite for React Native apps using Jest.

React Native apps have been gaining popularity since 2015 and are still growing consistently in 2021. With millions of apps migrating to the cross-platform space, it is crucial for developers to test them thoroughly. A huge portion of cross-platform apps also rely on local database updates to provide exclusive features.

Written by Sneh Pandya

Introduction to Jest

Testing allows developers to test the code that they write. One of the main goals of testing is to catch bugs earlier by running the tests locally or through a process. Unit tests can also help developers who may not have worked on the code to understand what the code should be doing when it executes.

Jest is a JavaScript testing library created by the same organization behind React: Facebook. But while Jest was created by the same developers who created React, it is not limited to only React – it can also be used with other frameworks, like Node, Angular, Vue, and Babel.

Set up React Native application

Let’s get started by setting up our project. To create a new application, run the commands as follows:

npm install -g expo-cli // To add Expo CLI on your machine

npx react-native init ReactNativeDBTesting // To set up a new React Native application

cd ReactNativeDBTesting

Next, we will use node-sqlite3 to test sqlite code using jest. It is compatible with packages like react-native-sqlite2 and react-native-sqlite-storage.

Let’s install the dependencies by running the command below in the terminal:

npm install --saveDev sqlite3@4.1.1 @types/websql@0.0.27 @types/sqlite@3.1.6    // SQLite

npm install --save-dev jest     // Jest

npm install --save-dev @testing-library/react-native @testing-library/jest-native

Make sure you are using the same SQLite version in Jest and the application environment.

Once successfully completed, you can verify that Jest has been added in package.json with the configuration:

{
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "preset": "react-native"
  }
}

Set up Jest for React Native

To use Jest, we need to follow a few steps and set up Jest in our React Native application.

  1. In the root directory of the project, add a new file and name it jest.config.js.

  2. Within jest.config.js, add the code below:

module.exports = {
  preset: 'react-native',
  setupFilesAfterEnv: ['@testing-library/jest-native/extend-expect'],
};

present is a preset that is used as a base for Jest’s configuration. A preset should point to an npm module that has a jest-preset.json or jest-preset.js file at the root.

setUpFilesAfterEnv specifies a list of paths to modules that run some code to configure or set up the testing framework before each test file in the suite is executed.

Define queries for tests

We will extract a query executor from the application’s environment for testing purposes.

export type SqlExecutor = {
  read: (query: string, args: Array<string>) => Promise<string[]>,
  write: (query: string, args: Array<string>) => Promise<string[]>,
}

Now, let’s define queries using the read and write of the executor in createUsers.ts, as shown below:

const CREATE_TABLE_IF_NOT_EXIST = `CREATE TABLE IF NOT EXISTS USERS (NAME TEXT);`

const GET_COUNT = `SELECT count(*) AS result FROM USERS`

export const createUsers = (executor: SqlExecutor) => ({
    createTable: () => executor.write(CREATE_TABLE_IF_NOT_EXIST),
    getCount: () => executor.read(GET_COUNT).then(result => Number.parseInt(result[0]))
})

Writing test for database

Before writing the test, we need to write an implementation of the executor.

const { promisify } = require('util');
import { Database } from 'sqlite3';
const createNodeSqlite2Executor = (db: Database): SqlExecutor => {
  const allPromise = promisify(db.all).bind(db);
  return {
    read: ((query, args) => allPromise(query, args)),
    write: ((query, args) => allPromise(query, args)),
  };
};

The executor returns a Promise with the result of read and write query operations.

Next, let’s add the test configuration for the database, as shown below:

const sqlite3 = require('sqlite3').verbose();
import { createUsers } from "./createUsers"

const inMemoryDb = new sqlite3.Database(':memory:');
const nodeExecutor = createNodeSqlite2Executor(inMemoryDb);
const userQueries = createUsers(nodeExecutor);

describe('usersQueries', () => {
    beforeEach(async () => {
        await userQueries.createTable();
    })
    it('getCount should return zero for empty table', async () => {
        const count = await userQueries.getCount();
        expect(count).toEqual(0);
    });
});

This test will describe the status of the Users table after communicating with the actual local database.

Add configuration to React Native application

After writing the test for our database, let’s implement SqlExtractor in our React Native application.

const parseSql(rs: SQLResultSet): string[] => {
  const result: Array<string> = new Array(rs.rows.length);
  for (let i = 0; i < rs.rows.length; i += 1) {
    result[i] = rs.rows.item(i);
  }
  return result;
}

const executeSql = (
  tr: SQLTransaction,
  query: string,
  ...args: string[]
):Promise<string[]> => new Promise((resolve, reject) => {
  tr.executeSql(
    query,
    args,
    (_, result) => resolve(parseSql(result)),
    (_, error) => {
      reject(error);
      return true;
    },
  );
});

export const createRnSqlite2Executor = (db: Database) : SqlExecutor => ({
  read: (query, ...args: string[]) => new Promise(
    (resolve) => db.readTransaction((tr) => resolve(executeSql(tr, query, ...args))),
  ),
  write: (query, ...args: string[]) => new Promise(
    (resolve) => db.transaction((tr) => resolve(executeSql(tr, query, ...args))),
  ),
});

Now we can use createRnSqlite2Executor in our React Native application (for example, using the React Context API).

Conclusion

We have covered the basics of database testing for SQLite with React Native applications using Jest. This approach can also potentially be used with the Detox framework as well.

How to build React Native apps on Codemagic

Start now

Useful links and resources


​
Sneh is a Senior Product Manager based in Baroda. He is a community organizer at Google Developers Group and co-host of NinjaTalks podcast. His passion for building meaningful products inspires him to write blogs, speak at conferences and mentor different talents.
You can reach out to him over Twitter (@SnehPandya18) or via email (sneh.pandya1@gmail.com).





Source link

ShareTweetSend
Previous Post

Carlyle Group CEO Kewsong Lee steps down suddenly, surprising firm executives

Next Post

Senate Dems pass long-awaited climate, tax and health care bill

Related News

Unlocking Potential: Exploring the FDE Model in Enterprise AI Solutions
Mobile

Unlocking Potential: Exploring the FDE Model in Enterprise AI Solutions

November 14, 2026
Unlocking the Scoop: Upcoming Sale Dates, Price Highlights, and Previous Bargains
Mobile

Unlocking the Scoop: Upcoming Sale Dates, Price Highlights, and Previous Bargains

November 14, 2026
Unlocking Website Security: The Marketbyte Edge in Open Source Solutions
Mobile

Unlocking Website Security: The Marketbyte Edge in Open Source Solutions

November 13, 2026
Uncovering the Best Solutions for Your Mobile Risk Concerns
Mobile

Uncovering the Best Solutions for Your Mobile Risk Concerns

November 12, 2026
Next Post
Senate Dems pass long-awaited climate, tax and health care bill

Senate Dems pass long-awaited climate, tax and health care bill

Discussion about this post

Subscribe To Our Newsletters

    Customer Support


    1251 Wilcrest Drive
    Houston, Texas
    77042 USA
    Call-832.795.1420
    e-mail – news@theinsightpost.com

    Subscribe To Our Newsletters

      Categories

      • Africa
      • Africa-East
      • African Sports
      • American Sports
      • Arts
      • Asia
      • Australia
      • Business
      • Business Asia
      • Business- Africa
      • Canada
      • Defense
      • Education
      • Egypt
      • Energy
      • Entertainment
      • Europe
      • European Soccer
      • Finance
      • Germany
      • Ghana
      • Health
      • Insight
      • International
      • Investing
      • Japan
      • Latest Headlines
      • Life & Living
      • Markets
      • Mobile
      • Movies
      • New Zealand
      • Nigeria
      • Politics
      • Scholarships
      • Science
      • South Africa
      • South America
      • Sports
      • Tech
      • Travel
      • Travel-Africa
      • UK
      • USA
      • Weather
      • World
      No Result
      View All Result

      Recent News

      Gators Shock Wildcats 21-14 in Thrilling Upset Amid Rollercoaster Season

      Gators Shock Wildcats 21-14 in Thrilling Upset Amid Rollercoaster Season

      November 15, 2026
      Government Announces Historic  Billion Investment in Energy Infrastructure Development

      Government Announces Historic $2 Billion Investment in Energy Infrastructure Development

      November 15, 2026
      Notre Dame Postgame Insights: Dive into Superchats with Westwood One Sports

      Notre Dame Postgame Insights: Dive into Superchats with Westwood One Sports

      November 15, 2026
      Transform Your Laptop Setup with These 5 Affordable Accessories

      Transform Your Laptop Setup with These 5 Affordable Accessories

      November 15, 2026
      • Home
      • Advertise With Us
      • About Us
      • Corporate
      • Consumer Rewards
      • Forum
      • Privacy Policy
      • Social Trends

      Theinsightpost ©2026 | All Rights Reserved. Theinsightpost is an Elnegy LLC company, registered in Texas, USA

      Welcome Back!

      Login to your account below

      Forgotten Password?

      Retrieve your password

      Please enter your username or email address to reset your password.

      Log In

      Add New Playlist

      We are using cookies to give you the best experience on our website.

      You can find out more about which cookies we are using or switch them off in .

      No Result
      View All Result
      • Home
      • Insight
      • Blog
      • Business
      • Entertainment
      • Health
      • Politics
      • Shop
        • Gift Shop
        • Value Shop
        • Store
        • Bargain Shop
        • Discount
      • Sports
      • Tech
      • Travel
      • USA
      • Video
      • World
        • Asia
        • Africa
        • South America
        • North America
        • Europe
        • Oceania

      Theinsightpost ©2026 | All Rights Reserved. Theinsightpost is an Elnegy LLC company, registered in Texas, USA

      The Insight Post
      Powered by  GDPR Cookie Compliance
      Privacy Overview

      This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

      Strictly Necessary Cookies

      Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

      Cookie Policy

      More information about our Cookie Policy