React Native单元测试基础知识及常见问题

基本用法

匹配器

  • toBe

    test('two plus two is four', () => {
      expect(2 + 2).toBe(4);
    });
    
  • toEqual (检查两个对象或集合是否完全相等)

  • toBeNull、toBeUndefined、toBeDefined、toBeTruthy、toBeFalsy

  • toBeGreaterThan、toBeLessThan

  • toBeCloseTo(浮点数判断)

  • toMatch(字符串判断)

    test('there is no I in team', () => {
      expect('team').not.toMatch(/I/);
    });   
    
  • toContain (集合判断)

  • toThrow

    function compileAndroidCode() {
      throw new Error('you are using the wrong JDK');
    }
    
    test('compiling android goes as expected', () => {
      expect(() => compileAndroidCode()).toThrow();
      expect(() => compileAndroidCode()).toThrow(Error);
    
      // You can also use the exact error message or a regexp
      expect(() => compileAndroidCode()).toThrow('you are using the wrong JDK');
      expect(() => compileAndroidCode()).toThrow(/JDK/);
    });
    

测试异步代码

  • done()

    test('the data is peanut butter', done => {
      function callback(data) {
        try {
          expect(data).toBe('peanut butter');
          done();
        } catch (error) {
          done(error);
        }
      }
    
      fetchData(callback);
    });
    
    //  如果未调用done,则默认会输出‘Error: thrown: "Exceeded timeout of 5000 ms for a test.’,想要详细的错误信息,可以使用try/catach
    
  • promise

    test('the data is peanut butter', () => {
      return fetchData().then(data => {
        expect(data).toBe('peanut butter');
      });
    });
    
    test('the fetch fails with an error', () => {
      expect.assertions(1);
      return fetchData().catch(e => expect(e).toMatch('error'));
    });
    
    // return Promise,jest 会自动处理resolve 和 reject 情况
    
  • .resolves/.rejects

    test('the data is peanut butter', () => {
      return expect(fetchData()).resolves.toBe('peanut butter');
    });
    
    test('the fetch fails with an error', () => {
      return expect(fetchData()).rejects.toMatch('error');
    });
    
  • async/await

    test('the data is peanut butter', async () => {
      const data = await fetchData();
      expect(data).toBe('peanut butter');
    });
    
    test('the fetch fails with an error', async () => {
      expect.assertions(1);
      try {
        await fetchData();
      } catch (e) {
        expect(e).toMatch('error');
      }
    });
    
  • combine async/await with .resolves/.rejects

    test('the data is peanut butter', async () => {
      await expect(fetchData()).resolves.toBe('peanut butter');
    });
    
    test('the fetch fails with an error', async () => {
      await expect(fetchData()).rejects.toMatch('error');
    });
    

初始化和销毁

  • beforeEach / afterEach

  • beforeAll / afterAll

  • describe

    /*Jest executes all describe handlers in a test file before it executes any of the actual tests. This is another reason to do setup and teardown inside before* and after* handlers rather than inside the describe blocks. Once the describe blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on.*/
    
    describe('outer', () => {
      console.log('describe outer-a');
    
      describe('describe inner 1', () => {
        console.log('describe inner 1');
        test('test 1', () => {
          console.log('test for describe inner 1');
          expect(true).toEqual(true);
        });
      });
    
      console.log('describe outer-b');
    
      test('test 1', () => {
        console.log('test for describe outer');
        expect(true).toEqual(true);
      });
    
      describe('describe inner 2', () => {
        console.log('describe inner 2');
        test('test for describe inner 2', () => {
          console.log('test for describe inner 2');
          expect(false).toEqual(false);
        });
      });
    
      console.log('describe outer-c');
    });
    
    // describe outer-a
    // describe inner 1
    // describe outer-b
    // describe inner 2
    // describe outer-c
    // test for describe inner 1
    // test for describe outer
    // test for describe inner 2
    

模拟函数

  • 什么是mock functions

    Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new, and allowing test-time configuration of return values.

    The goal for mocking is to replace something we don’t control with something we do

    mock函数提供的特性如下:

    • 捕获调用
    • 设置返回值
    • 改变实现
  • 创建模拟函数

    // 通过jest.fn() 创建模拟函数,可以测试函数调用状态和调用参数等信息
    
    function forEach(items, callback) {
      for (let index = 0; index < items.length; index++) {
        callback(items[index]);
      }
    }
    
    const mockCallback = jest.fn(x => 42 + x);
    forEach([0, 1], mockCallback);
    
    // The mock function is called twice
    expect(mockCallback.mock.calls.length).toBe(2);
    
    // The first argument of the first call to the function was 0
    expect(mockCallback.mock.calls[0][0]).toBe(0);
    
    // The first argument of the second call to the function was 1
    expect(mockCallback.mock.calls[1][0]).toBe(1);
    
    // The return value of the first call to the function was 42
    expect(mockCallback.mock.results[0].value).toBe(42);
    
  • 模拟返回值

    const myMock = jest.fn();
    console.log(myMock());
    // > undefined
    
    myMock.mockReturnValueOnce(10).mockReturnValueOnce('x').mockReturnValue(true);
    
    console.log(myMock(), myMock(), myMock(), myMock());
    // > 10, 'x', true, true
    
  • 模拟模块

    users.js
    ---------------------------------------------------
    import axios from 'axios';
    
    class Users {
      static all() {
        return axios.get('/users.json').then(resp => resp.data);
      }
    }
    
    export default Users;
    ---------------------------------------------------
    test.js
    ---------------------------------------------------
    import axios from 'axios';
    import Users from './users';
    
    jest.mock('axios');
    
    test('should fetch users', () => {
      const users = [{name: 'Bob'}];
      const resp = {data: users};
      axios.get.mockResolvedValue(resp);
    
      // or you could use the following depending on your use case:
      // axios.get.mockImplementation(() => Promise.resolve(resp))
    
      return Users.all().then(data => expect(data).toEqual(users));
    });
    
    • jest.spyOn()

      jest.mock()通常无法访问到原始实现,spyOn可以修改原始实现,且稍后可以恢复

测试覆盖率

yarn test --coverage

Image_20211222094834.png

Stats为语句测试覆盖率。Branch为条件分支测试覆盖率。Funcs为函数覆盖率。Lines为行覆盖率。Uncovered Line为未覆盖的行号

快照

Image_20211222155005.png
test('renders correctly', () => {
    const tree = renderer.create(<He/>).toJSON();
    expect(tree).toMatchSnapshot();
});

错误集锦

ES6 support

  • FAIL  src/__tests__/navigation.test.ts
      ● Test suite failed to run
    
        Jest encountered an unexpected token
    
        This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
    
        By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
    
        Here's what you can do:
         • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
         • If you need a custom transformation specify a "transform" option in your config.
         • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
    
        You'll find more details and examples of these config options in the docs:
        https://jestjs.io/docs/en/configuration.html
    
        Details:
    
        /Users/jyurek/Development/react-navigation-error-replication/node_modules/react-navigation-stack/dist/index.js:2
        import { Platform } from 'react-native';
               ^
    
        SyntaxError: Unexpected token {
    
          2 | import {ExampleScreen} from './screens/ExampleScreen';
          3 |
        > 4 | const Navigation = createStackNavigator({
            |                    ^
          5 |   ExampleScreen: {
          6 |     screen: ExampleScreen,
          7 |   },
    
          at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:451:17)
          at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:493:19)
          at Object.get createStackNavigator [as createStackNavigator] (node_modules/react-navigation/src/react-navigation.js:107:12)
          at Object.<anonymous> (src/navigation.ts:4:20)
    

    此类问题为native module使用了ES语法,而jest默认是不支持ES语法的。解决方法是使用babel, 自定义babel配置, jest自动使用babel做语法转换。但是又因为jest默认会忽略'node_modules', 即'node_modules'下的内容不会做语法转换。解决方法为在jest配置中添加‘transformIgnorePatterns’属性:

    {
      "transformIgnorePatterns": [
        "node_modules/(?!(react-native|react-native-button)/)"
      ]
    }
    

mock NativeModule

  • Test suite failed to run
    
        [@RNC/AsyncStorage]: NativeModule: AsyncStorage is null.
    
        To fix this issue try these steps:
    
          • Run `react-native link @react-native-async-storage/async-storage` in the project root.
    
          • Rebuild and restart the app.
    
          • Run the packager with `--reset-cache` flag.
    
          • If you are using CocoaPods on iOS, run `pod install` in the `ios` directory and then rebuild and re-run the app.
    
          • If this happens while testing with Jest, check out docs how to integrate AsyncStorage with it: https://react-native-async-storage.github.io/async-storage/docs/advanced/jest
    
        If none of these fix the issue, please open an issue on the Github repository: https://github.com/react-native-async-storage/react-native-async-storage/issues
    

    此类问题为需要mock对应模块,一般对应模块文档会有相关mock实现

React is not defined

  • React is not defined
    ReferenceError: React is not defined
        at Object.<anonymous> (/Users/daniel/Desktop/EcovacsHomeRN/__tests__/RobotMsgTabPages.test.js:6:39)
        at Promise.then.completed (/Users/daniel/Desktop/EcovacsHomeRN/node_modules/jest-circus/build/utils.js:391:28)
        at new Promise (<anonymous>)
        at callAsyncCircusFn (/Users/daniel/Desktop/EcovacsHomeRN/node_modules/jest-circus/build/utils.js:316:10)
        at _callCircusTest (/Users/daniel/Desktop/EcovacsHomeRN/node_modules/jest-circus/build/run.js:218:40)
        at processTicksAndRejections (node:internal/process/task_queues:96:5)
        at _runTest (/Users/daniel/Desktop/EcovacsHomeRN/node_modules/jest-circus/build/run.js:155:3)
        at _runTestsForDescribeBlock (/Users/daniel/Desktop/EcovacsHomeRN/node_modules/jest-circus/build/run.js:66:9)
        at run (/Users/daniel/Desktop/EcovacsHomeRN/node_modules/jest-circus/build/run.js:25:3)
        at runAndTransformResultsToJestFormat (/Users/daniel/Desktop/EcovacsHomeRN/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapterInit.js:170:21)
    
    

    此情况一般为在用react-test-renderer做组件测试时,在import renderer from 'react-test-renderer';之前需要import React from "react";

nativeBridge

  • Cannot read property 'rnConnection' of undefined
    TypeError: Cannot read property 'rnConnection' of undefined
    

    在测试文件中mock, NativeModules.Bridge = {rnConnection: jest.fn()}

SyntaxError

  •  SyntaxError: /Users/daniel/Desktop/EcovacsHomeRN/node_modules/@react-native/polyfills/error-guard.js: Unexpected token, expected "," (51:22)
      
          49 |     _globalHandler && _globalHandler(error, true);
          50 |   },
        > 51 |   applyWithGuard<TArgs: $ReadOnlyArray<mixed>, TOut>(
             |                       ^
          52 |     fun: Fn<TArgs, TOut>,
          53 |     context?: ?mixed,
          54 |     args?: ?TArgs,
    

    此为babel配置了@babel/plugin-syntax-typescript插件导致babel只做TS语法解析,而不做语法转换,在jest组件测试会报语法错误。解决方案为使用@babel/plugin-transform-typescript或者 @babel/preset-typescript 同时支持语法解析和转化.文档地址:https://babel.dev/docs/en/babel-plugin-syntax-typescript

小试牛刀

  • 测试组件方法调用

    import React from "react";
    import RobotMsgTabPages from "../js/AppCommon/robot/RobotMessage/RobotMsgTabPages";
    import renderer from 'react-test-renderer';
    import MessageCenterHomePage from "../js/AppCommon/messageCenter/MessageCenterHomePage";
    import {NativeModules} from "react-native";
    import RobotEmptyView from "../js/AppCommon/robot/RobotMessage/CommonComponent/RobotEmptyView";
    import {SwipeListView} from "react-native-swipe-list-view";
    
    it('should ropRobotTabMsgList callback', function () {
    
        const state = {routeName : '', params: {did : '13',title : '123', hasUnreadMsg : true,item : '',changeUnread : true}}
        const getParam = params => {return true};
        const addListener = (params,callback) => {}
    
        const component = renderer.create(<RobotMsgTabPages navigation={{"state":state, "getParam":getParam, "addListener" : addListener}}/>).root;
        const swipeListView = component.findByType(RobotEmptyView);
        console.log(swipeListView.props.onPress)
    });
    
  • 测试接口调用

    import { ropRobotProductMsgList} from '../js/InternalModule/api/MessageCenterApi'
    // import {fetch} from "@react-native-community/netinfo";
    // jest.mock('../js/InternalModule/api/MessageCenterApi')
    
    beforeAll(() => {
        RopConstants.iotServerUrl = "dadadadad"
    })
    
    test('mock modules', async () => {
        // fetch.mockResolvedValue('ddad');
        // fetch.mockReturnValue('dadaad');
        // ropRobotProductMsgList.mockImplementation(() => {
        //     return new Promise((resolve, reject) => {
        //        reject('dadaad')
        //     });
        // })
        await expect(ropRobotProductMsgList({'a' : 'ddaq'})).rejects.toEqual('dadaad');
    });
    
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,384评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,845评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,148评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,640评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,731评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,712评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,703评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,473评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,915评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,227评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,384评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,063评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,706评论 3 324
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,302评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,531评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,321评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,248评论 2 352

推荐阅读更多精彩内容