如何测试React Native模块?

Cli*_*lip 35 javascript mocha.js reactjs react-native

I developed a React Native module (wrapping an SDK) and I’m interested in creating some unit tests using mocha. I’m not very familiar with mocha, but I can’t exactly figure out how to proceed.

I have my react native module, call it react-native-mymodule which I can use in an app by doing:

npm install react-native-mymodule

react-native link react-native-mymodule

Then I can import my module with:

import MySDK from "react-native-mymodule”;

I’m trying to do a similar thing with unit tests. In my root directory I have a test/ directory which is where I want to hold all my unit tests.

My simple test file in test/sdk.tests.js

import MySDK from "react-native-mymodule”;
var assert = require('assert');


describe(‘MySDK’, function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal([1, 2, 3].indexOf(4), -1);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

I’ve tried modifying a tutorial I found online on compiling modules, but haven’t had any luck. This is a file test/setup.js:

import fs from 'fs';
import path from 'path';
import register from 'babel-core/register';

const modulesToCompile = [
  'react-native-mymodule’
].map((moduleName) => new RegExp(`${moduleName}`));


const rcPath = path.join(__dirname, '..', '.babelrc');
const source = fs.readFileSync(rcPath).toString();
const config = JSON.parse(source);
config.ignore = function(filename) {
  if (!(/\/node_modules\//).test(filename)) {
    return false;
  } else {
    return false;
  }
}

register(config);
Run Code Online (Sandbox Code Playgroud)

.babelrc in the root level of my module

{
  "presets": ["flow", "react-native"],
    "plugins": [
      ["module-resolver", {
        "root": [ "./js/" ]
      }]
    ]
}

Run Code Online (Sandbox Code Playgroud)

I have a test/mocha.opts file:

--require babel-core/register
--require test/setup.js
Run Code Online (Sandbox Code Playgroud)

I’m invoking mocha with: ./node_modules/mocha/bin/mocha and I get an error:

Error: Cannot find module 'react-native-mymodule'

谁能建议我测试反应本机模块的最佳方法?

Tom*_*m M 5

如果您想测试本机模块,我建议如下:

1. 端到端测试

Node.js 独立版无法解释本机模块。如果您想在应用程序的上下文中测试本机模块,您需要使用 appium/webdriverio 创建 e2e 测试,而不是使用 mocha 编写单元测试。

这样,您实际上就启动了一个安装了应用程序的模拟器。

资源:

2. 单元测试

如果您想为本机模块编写单元测试,请使用编写本机模块所用的语言来编写它们

资源:


除此之外,您必须模拟模块。