jest单元测试(二)

假设我们在之前准备工作都已成功,接下来就开始愉快地玩转jest

自动模拟(auto mock)

在package.json开启,默认关闭

"jest": {
    "automock": true
}

开启后,自动捕获函数的调用, 官方栗子:

import utils from '../utils';

test('if utils are mocked', () => {
  expect(utils.authorize.mock).toBeTruthy();
  expect(utils.isAuthorized.mock).toBeTruthy();
});

test('mocked implementation', () => {
  utils.authorize.mockReturnValue('mocked_token');// 手动设置返回值
  utils.isAuthorized.mockReturnValue(true);

  expect(utils.authorize()).toBe('mocked_token');
  expect(utils.isAuthorized('not_wizard')).toBeTruthy();
});

代码中没有mock方法调用,实际上已经模拟了utils的相关函数,值得注意的是,如果没有对mock的函数进行自定义的实现,一般返回undefined。如果既开启自动mock,又手动模拟的,后面会覆盖前者。

全局开启自动模拟后,局部需要关闭的时候,用jest.disableAutomock方法关闭,栗子:

import utils from '../utils';

jest.disableAutomock();

test('original implementation', () => {
  expect(utils.authorize()).toBe('token');
});

偶尔,也会需要用到原始的函数,用genMockFromModule方法获取,栗子:

import utils from '../utils';

test('implementation created by automock', () => {
  expect(utils.authorize('wizzard')).toBeUndefined();
  expect(utils.isAuthorized()).toBeUndefined();
});

test('implementation created by jest.genMockFromModule', () => {
  const utils = jest.genMockFromModule('../utils').default;
  utils.isAuthorized = jest.fn(secret => secret === 'not wizard');

  expect(utils.authorize.mock).toBeTruthy();
  expect(utils.isAuthorized('not wizard')).toEqual(true);
});

手动模拟(manual mock)

对node_module中的包进行mock时,一般在项目根目录下创建mocks目录,再创建相应的文件。
这里需要注意,如果是引入scope module,需要在mocks目录下,直接创建@scope目录。
对自己开发的模块进行mock时,一般是在该模块文件所在的目录下创建mocks目录,再创建相应的文件
工程目录如下:

jest单元测试(二)_第1张图片
image.png

模块化模拟 (module mock)

可以模块中的部分函数进行模拟,官方栗子:

import defaultExport, {apple, strawberry} from '../fruit';

jest.mock('../fruit', () => {
  const originalModule = require.requireActual('../fruit');
  const mockedModule = jest.genMockFromModule('../fruit');

  //Mock the default export and named export 'apple'.
  return Object.assign({}, mockedModule, originalModule, {
    apple: 'mocked apple',
    default: jest.fn(() => 'mocked fruit'),
  });
});

it('does a partial mock', () => {
  const defaultExportResult = defaultExport();
  expect(defaultExportResult).toBe('mocked fruit');
  expect(defaultExport).toHaveBeenCalled();

  expect(apple).toBe('mocked apple');
  expect(strawberry()).toBe('strawberry');
});

以上代码只模拟了fruit中的default与apple函数,保留了其他函数

也可以在一个文件中对相同的模块做不同的模拟,栗子:

describe('define mock per test', () => {
  beforeEach(() => {
    jest.resetModules();
  });

  it('uses mocked module', () => {
    jest.doMock('../fruit', () => ({
      apple: 'mocked apple',
      default: jest.fn(() => 'mocked fruit'),
      strawberry: jest.fn(() => 'mocked strawberry'),
    }));
    const {apple, strawberry, default: defaultExport} = require('../fruit');

    const defaultExportResult = defaultExport();
    expect(defaultExportResult).toBe('mocked fruit');
    expect(defaultExport).toHaveBeenCalled();

    expect(apple).toBe('mocked apple');
    expect(strawberry()).toBe('mocked strawberry');
  });

  it('uses actual module', () => {
    jest.dontMock('../fruit');
    const {apple, strawberry, default: defaultExport} = require('../fruit');

    const defaultExportResult = defaultExport();
    expect(defaultExportResult).toBe('banana');

    expect(apple).toBe('apple');
    expect(strawberry()).toBe('strawberry');
  });
});

快照测试 (Snapshot Test)

快照测试主要用于UI的回归测试,第一次运行测试的时候,会在tests目录下生成snapshots目录与以及相应的组件并以snap为扩展名,之后每次改动,都会在测试结果中标记出变动,如果是你想要的变动,可以运行 jest --updateSnapshot 来更新快照,栗子:

'use strict';

import 'react-native';
import React from 'react';
import Intro from '../Intro';

// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';

it('renders correctly', () => {
  const tree = renderer.create().toJSON();
  expect(tree).toMatchSnapshot();
});

// These serve as integration tests for the jest-react-native preset.
it('renders the ActivityIndicator component', () => {
  const ActivityIndicator = require('ActivityIndicator');
  const tree = renderer
    .create()
    .toJSON();
  expect(tree).toMatchSnapshot();
});

it('renders the Image component', done => {
  const Image = require('Image');
  Image.getSize('path.jpg', (width, height) => {
    const tree = renderer.create().toJSON();
    expect(tree).toMatchSnapshot();
    done();
  });
});

it('renders the TextInput component', () => {
  const TextInput = require('TextInput');
  const tree = renderer
    .create()
    .toJSON();
  expect(tree).toMatchSnapshot();
});

it('renders the ListView component', () => {
  const ListView = require('ListView');
  const Text = require('Text');
  const dataSource = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 !== r2,
  }).cloneWithRows(['apple', 'banana', 'kiwi']);
  const tree = renderer
    .create(
       {rowData}}
      />
    )
    .toJSON();
  expect(tree).toMatchSnapshot();
});

值得注意的是,UI测试依赖react-test-renderer模块,并且要在引入 react-native之后。

总结

本节主要介绍了mock的三种方式,并用了官方的例子来说明。

你可能感兴趣的:(jest单元测试(二))