question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Realm queries randomly returning null during unit tests.

See original GitHub issue

We’re running into some big issues trying to write tests for realm object serialisation. This pattern seems to work flawlessly in the simulator and on the device, but in tests it’s not reliable. We’ve tried passing inMemory: true to the realm config and still no dice.

Goals

Reliably test Realm serialisation using Jest

Expected Results

A realm query consistently returns the same result.

Actual Results

Realm randomly returns null for a query that should have data. (Happens more often on some machines than others).

We’ve written this code based on the example app. We’ve been trying for a day to crack this but we just cannot figure it out. It fails every second time on our CI and 1/10 times on our dev machines.

Steps to Reproduce

N/a

Code Sample

realm.js

import Realm from 'realm';
import schema from './schema';

const realmConfig = {
  schema: schema,
  deleteRealmIfMigrationNeeded: true
}

export default new Realm(realmConfig);

accountManage.js

import realm from '@/models/realm';

import Account from '@/models/schema/Account';

export function saveAccounts(accountsData) {
  return new Promise((success, failure) => {
    try {
      realm.write(() => {
        const accounts = accountsData.
          map(accountData => realm.create('Account', Account.mapping(accountData), true))
        success(accounts)
      })
    } catch (e) {
      failure(e)
    }
  })
}

Account.js

import Realm from 'realm'
import realm from '@/models/realm'
import Currency from './Currency'
import Balance from './Balance'
import { currentUser } from '@/managers/model/userManager'

class Account {}

Account.schema = {
  name: 'Account',
  primaryKey: 'uuid',
  properties: {
    uuid: 'string?',
    currency: 'Currency',
    type: 'string?'
  }
}

Account.mapping = function(data) {
  const isoCode = data['currency'];
const query = `isoCode = "${isoCode}"`;
  const currency = realm.objects('Currency').filtered(query)[0]; <--- This randomly returns null ONLY during unit tests on some machines, specifically our CI
  return {
    'uuid': data['uuid'],
    'currency': currency,
    'type': data['type']
  }
}

export default Account

accountsManager.spec.js

import realm from '@/models/realm'
import { deleteAllData } from '@/models/realmUtils'
import { saveAccounts } from '../accountManager'
import accountsStub from '@/stubs/Accounts/get-accounts-success'

afterAll(() => {
  deleteAllData()
});

describe('Save Accounts', () => {
  beforeAll(() => {
    realm.write(() => {
      realm.create('Currency', {
        name: 'Australian Dollar',
        isoCode: 'AUD',
      } , true)
    realm.create('Currency', {
      name: 'Great Britain Pound',
      isoCode: 'GBP',
    } , true)
    });
  });

  test('it creates the right amount of accounts', () => {
    expect.assertions(1);
    return saveAccounts(accountsStub.accounts).then(accounts => {
      expect(accounts.length).toBe(4);
    });
  });

  test('it seralizes the accounts correctly', () => {
    expect.assertions(2);
    return saveAccounts(accountsStub.accounts).then(accounts => {
      const account = accounts[0]
      expect(account.uuid).toBe('439fad52-3138-4fda-808f-36a880a67f20');
      expect(account.currency.name).toBe('Australian Dollar') <--- This assertion inconsistently fails
    });
  });
})

Version of Realm and Tooling

  • React 16.4.1
  • React Native 0.56.0
  • Realm: 2.13.0
  • Node: 9.11.2
  • Jest: 23.5.0
  • Client OS & Version: Mac OSX: 10.13.6
  • Which debugger for React Native: None

Any thoughts?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:12 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
ironagecommented, Aug 20, 2018

Can you send the updated code, and the console logs? Make sure that success(accounts) from saveAccounts is outside of the write block, otherwise it will return before committing the write transaction. Did you find out if you need to return something from beforeAll? One other thing to check is if your CI is running the test at the same path or in an isolated environment. Since you don’t specify a file name for the realm in the config, it is assigned a default name which will be shared if the test is run from the same location again; this could cause a race condition because of the deleteAll if testing is run concurrently.

1reaction
aburycommented, Aug 18, 2018

Ah k, that’s great to hear 👍. I’ll let you know how we go!

Read more comments on GitHub >

github_iconTop Results From Across the Web

android - Realm Unit Testing - Stack Overflow
While instrumentation tests seem easy, unit test are quite involved: ... return the mock query. when(mockRealm.where(Person.class)).
Read more >
Realm: Create reactive mobile apps in a fraction ... - MongoDB
The unitTestExample shows how you can write unit tests when working with Realm. ... Queries on normal Realm instances must continue to use...
Read more >
Component Reference - Apache JMeter - User's Manual
Several test elements use JMeter properties to control their behaviour. These properties are normally resolved when the class is loaded.
Read more >
Modern Best Practices for Testing in Java - Philipp Hauer's Blog
Modern best practices for unit tests and integration tests in Java ... Maintainable and readable test code is crucial to establish a good ......
Read more >
Create reactive mobile apps in a fraction of the time - Realm
Realm Swift is the first database built for mobile. ... In your unit test target's “Build Settings”, add the parent path to RealmSwift.framework...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found