使用Jest测试React Native应用程序

时间:2016-05-17 23:16:09

标签: javascript unit-testing react-native jestjs

我一直试图让Jest使用我的反应原生项目而没有太多运气。似乎大多数线程都是被黑客攻击的解决方案,以便让事情正常运行,我似乎无法克服我面临的最后一个障碍。

问题

尝试运行以下代码时出现以下错误。如果我在jestSupport / env.js文件中模拟react-native我可以通过错误,但显然我不能使用任何结构(如AsyncStorage)来实际测试我的代码(因为我只有模拟功能)。

问题

有没有人对如何解决这个问题有什么建议?

在这个阶段,我愿意尝试任何事情,包括废弃与我有关的所有测试并再次尝试。如果是这种情况,我需要遵循一些指导原则,因为React Native文档在Jest方面可能已经过时,而且我对React场景相对较新。

错误

Runtime Error
Error: Cannot find module 'ReactNative' from 'react-native.js'
    at Runtime._resolveNodeModule (/Users/Yulfy/Downloads/COMPANY-Mobile/node_modules/jest-cli/src/Runtime/Runtime.js:451:11)
    at Object.<anonymous> (/Users/Yulfy/Downloads/COMPANY-Mobile/node_modules/react-native/Libraries/react-native/react-native.js:181:25)
    at Object.<anonymous> (/Users/Yulfy/Downloads/COMPANY-Mobile/network/connections.js:8:18)

测试代码

jest.unmock('../network/connections');

import Authorisation from '../network/connections';

describe('connections', () => {
  it('Should store and retrieve a mocked user object', () => {
    Auth = new Authorisation();
    const TEST_STRING = "CONNECTION TEST PASS";
    var userObj = {
      test_string: TEST_STRING
    };
    Auth._localStore(userObj, (storeRes) => {
      Auth._localRetrieve((retRes) => {
        expect(retRes.test_string).toEqual(TEST_STRING);
      });
    });
  });
});

connection.js

/*
*  All returns should give the following structure:
*  {isSuccess: boolean, data: object}
*/


import React, { Component } from 'react';
import { AsyncStorage } from 'react-native';

const Firebase = require('firebase');
const FIREBASE_URL = 'https://COMPANY-test.firebaseio.com';
const STORAGE_KEY = 'USER_DATA';
class Authorisation{
  _ref = null;
  user = null;

  constructor(){

  }

  getOne(){return 1;}
  _setSystemUser(userObj, authObj, callback){
    var ref = this.connect();
    if(ref === null){
      callback({isSuccess:false, data:{message:"Could not connect to the server"}});
    }
    ref = ref.child('users').child(authObj.uid);
    ref.once("value", function(snapshot){
      if(snapshot.exists()){
        callback({isSuccess:false, data:{message:"Email is currently in use"}});
        return;
      }
      ref.set(userObj, function(error){
        if(error){
          callback({isSuccess:false, data:error});
        }else{
          callback({isSuccess:true, data:authObj});
        }
      });
    });
  }

  _localStore(userObj, callback){
    AsyncStorage.setItem(STORAGE_KEY, userObj, (error) => {
      console.log("_localStore::setItem -> ", error);
      if(error){
        callback({
          isSuccess:false,
          data:'Failed to store user object in storage.'
        });
      }else{
        callback({
          isSuccess:true,
          data: userObj
        });
      }
    });
  }
  _localRetrieve(callback){
    AsyncStorage.getItem(STORAGE_KEY, (error, res) => {
      console.log("_localStore::getItem:error -> ", error);
      console.log("_localStore::getItem:result -> ", res);
      if(error){
        callback({
          isSuccess:false,
          data:error
        });
      }else{
        callback({
          isSuccess: true,
          data: res
        });
      }
    });
  }

  connect(){
    if(this._ref === null){
      _ref = new Firebase(FIREBASE_URL);
    }
    return _ref;
  }

  getUser(){

  }

  isLoggedIn(){

  }

  registerUser(userObj, callback){
    var ref = this.connect();
    if(ref === null){
      callback({isSuccess:false, data:{message:"Could not connect to the server"}});
    }
    var that = this;
    ref.createUser({
      email: userObj.username,
      password: userObj.password
    }, function(error, userData){
      if(error){
        callback({isSuccess:false, data:error});
        return;
      }
      var parseObj = {
        email: userObj.username,
        fullName: userObj.fullName
      };
      that.loginUser(parseObj, function(res){
        if(res.isSuccess){
          that._setSystemUser(parseObj, res.data, callback);
        }else{
          callback(res);//Fail
        }
      });
    });
  }

  loginUser(userObj, callback){
    var ref = this.connect();
    if(ref === null){
      callback({isSuccess:false, data:{message:"Could not connect to the server"}});
    }
    ref.authWithPassword({
      email: userObj.email,
      password: userObj.password
    }, function(error, authData){
      if(error){
        callback({isSuccess:false, data:error.message});
      }else{
        callback({isSuccess:true, data:authData});
      }
    });

  }
}

export default Authorisation;

如果你已经读过这篇文章了,谢谢你的时间!

-Yulfy

2 个答案:

答案 0 :(得分:10)

<强> TL; DR

我在这个GitHub Repo中有一个运行最新版本React Native(v0.28.0)的Jest的工作示例。

-

经过一段时间调查此问题后,我终于找到了解决方案。

有一些与Jest集成的React Native应用程序的在线示例,但不幸的是,您不能简单地将代码复制并粘贴到代码库中并期望它能够正常工作。这是因为RN版本的差异。

v0.20.0之前的React Native版本在包装程序(.babelrc)中包含node_modules/react-native/packager/react-packager/.babelrc文件,其中一些在线示例直接将其包含在package.json中。但是,版本v0.20.0及更改为不再包含此文件,这意味着您无法再尝试包含该文件。因此,我建议您使用自己的.babelrc文件并对自己的预设和插件进行definte。

我不知道你的package.json文件是什么样的,但是解决这个问题是一个非常重要的部分。

{
    "name": "ReactNativeJest",
    "version": "0.0.1",
    "jest": {
        "scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
        "unmockedModulePathPatterns": [
            "node_modules"
        ],
        "verbose": true,
        "collectCoverage": true
    },
    "scripts": {
        "test": "jest"
    },
    "dependencies": {
        "react": "^15.1.0",
        "react-native": "^0.27.2"
    },
    "devDependencies": {
        "babel-core": "^6.4.5",
        "babel-jest": "^12.1.0",
        "babel-plugin-transform-regenerator": "^6.0.18",
        "babel-polyfill": "^6.0.16",
        "babel-preset-react-native": "^1.9.0",
        "babel-types": "^6.1.2",
        "chai": "^3.5.0",
        "enzyme": "^2.3.0",
        "jest-cli": "^12.1.1",
        "react-addons-test-utils": "^15.1.0",
        "react-dom": "^15.1.0"
    }
}

另一个重要的部分是嘲笑React Native。我创建了一个__mocks__/react-native.js文件,如下所示:

'use strict';

var React = require('react');
var ReactNative = React;

ReactNative.StyleSheet = {
    create: function(styles) {
        return styles;
    }
};

class View extends React.Component {}
class Text extends React.Component {}
class TouchableHighlight extends React.Component {}

// Continue to patch other components as you need them
ReactNative.View = View;
ReactNative.Text = Text;
ReactNative.TouchableHighlight = TouchableHighlight;

module.exports = ReactNative;

通过猴子修补这样的React Native函数,您可以成功避免在尝试运行测试时遇到的奇怪的Jest错误。

最后,确保在项目的根目录中创建一个.babelrc文件,该文件至少包含以下几行:

{
    "presets": ["react-native"],
    "plugins": [
        "transform-regenerator"
    ]
}

此文件将用于告知babel如何正确转换ES6代码。

完成此设置后,使用React Native运行Jest应该没有问题。我相信React Native的未来版本可以更容易地将两个框架集成在一起,但是这种技术可以完美地适用于当前版本:)

修改

您可以使用react-native-mock库为您进行模拟,而不是手动模拟__mocks__/react-native.js文件中的ReactNative元素(确保将库添加到package.json文件中):

// __mocks__/react-native.js

module.exports = require('react-native-mock');

我更新了我的GitHub Repo示例以演示此方法。

答案 1 :(得分:-1)

您是否尝试在测试文件中模拟react-native?

它适用于我的测试用例:

jest.dontMock(`../my-module-that-uses React-native.AsyncStorage`);

jest.setMock(`react-native`, {
  AsyncStorage: {
    multiGet: jest.fn(),
  },
});

const ReactNative = require(`react-native`);
const {AsyncStorage, } = ReactNative;

const myModule = require(`../my-module-that-uses React-native.AsyncStorage`);

// Do some tests and assert ReactNative.AsyncStorage.multiGet calls