简体   繁体   中英

How to Start Unit Testing in React Native using jest for constant

I m new to Unit Test and currently writing Unit Test for my TypeScript app using Jest. I m using a custom package named common-packages where i store all of my constant, something simple like this

const CLIENT_ID = 1231123123;
const TEXT = {
  Discover:"Discover",
  loading: 'loading',
  Type: "Testing",
}
const Constants = {
  TEXT,
  CLIENT_ID,
} as const;

export default Constants;

on my package, index.tsx. i export the Constant

export { default as Constants } from "./constants";

And the function that i want to test is this

import {Constants} from 'common-packages';

export const lockNextCardIfUncompleted = (data: any[]) => {
  if (data.length !== 0) {
    const locked = data.filter((e: any) => e.Type === Constants.TEXT.Type );
    if (locked.length === 0) return false;
    return true;
  }
  return false;
};

i have tried writing a unit test for lodash like this and it is working

const lodash = require('lodash')
test("repeat", () => {
expect(lodash.repeat("A",3)).toBe("AAA");
})

But for the unit test that have common-packages, it failed

import {
  lockNextCardIfUncompleted,
} from './fileName';

test('should return locked', () => {
  expect(
    lockNextCardIfUncompleted([
      {
        Type: 'A',
      },
    ]),
  ).toBe(false);
  expect(
    lockNextCardIfUncompleted([
      {
        Type: 'Testing,
      },
    ]),
  ).toBe(true);
});

It return TypeError: Cannot read property 'TEXT' of undefined . So the test didnt recognize the Constant from common-package . can anybody please help me solve this issue? thank you

You are using Default Exports , NOT Named Exports .

So you need to import the constants like this:

import Constants from 'common-packages';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM