jerryni / blog

:dog: :dog: :dog:
https://github.com/jerryni/blog/issues
11 stars 4 forks source link

Jest - Snapshot Testing入门笔记 #27

Open jerryni opened 6 years ago

jerryni commented 6 years ago

hello world

在线 demo: https://github.com/facebook/jest.git

jest/examples/snapshot里的目录结构:

├── Clock.react.js
├── Link.react.js
├── __tests__
│   ├── __snapshots__
│   │   ├── clock.react.test.js.snap
│   │   └── link.react.test.js.snap
│   ├── clock.react.test.js
│   └── link.react.test.js
├── node_modules
└── package.json

实例

运行下面的测试代码:

import React from 'react';
import Link from '../Link.react';
import renderer from 'react-test-renderer';

it('renders correctly', () => {
  const tree = renderer
    .create(<Link page="http://www.facebook.com">Facebook</Link>)
    .toJSON();
  expect(tree).toMatchSnapshot();
});

将生成如下的snapshot文件:

exports[`renders correctly 1`] = `
<a
  className="normal"
  href="http://www.facebook.com"
  onMouseEnter={[Function]}
  onMouseLeave={[Function]}
>
  Facebook
</a>
`;
it('will check the matchers and pass', () => {
  const user = {
    createdAt: new Date(),
    id: Math.floor(Math.random() * 20),
    name: 'LeBron James',
  };

  expect(user).toMatchSnapshot({
    createdAt: expect.any(Date),
    id: expect.any(Number),
  });
});

最佳实践

exports[<UserName /> should render Alan Turing] = `

Alan Turing


## 后续参考资料
基础:[Snapshot Testing · Jest](https://facebook.github.io/jest/docs/en/snapshot-testing.html)
由来:[Jest 14.0: React Tree Snapshot Testing · Jest](https://facebook.github.io/jest/blog/2016/07/27/jest-14.html)
初印象:https://benmccormick.org/2016/09/19/testing-with-jest-snapshots-first-impressions/
视频推荐:[Use Jest’s Snapshot Testing Feature from @kentcdodds on @eggheadio](https://egghead.io/lessons/javascript-use-jest-s-snapshot-testing-feature?pl=testing-javascript-with-jest-a36c4074)
jerryni commented 5 years ago

一个实战的内部组件库配置参考和说明

module.exports = {
  'moduleFileExtensions': [
    'js',
    'vue'
  ],
  'moduleDirectories': [
    'node_modules',
    'packages'
  ],
  'moduleNameMapper': { // 相当于webpack里的alias
    '^packages/(.*)$': '<rootDir>/packages/$1',
    '^docs/(.*)$': '<rootDir>/docs/examples-docs/$1',
    '^examples-dist/(.*)$': '<rootDir>/docs/examples-dist/$1',
    '^test/(.*)$': '<rootDir>/test/$1'
  },
  'transform': { // 相当于webpack里的loader
    '^.+\\.js$': '<rootDir>/node_modules/babel-jest',
    '.*\\.(vue)$': '<rootDir>/node_modules/vue-jest',
    '.+\\.(css|styl|less|sass|scss)$': 'jest-transform-css'
  },
  'transformIgnorePatterns': [ // 不转化的东西,这里可以排除掉转化的库,比如vant
    '/node_modules/(?!vant)'
  ],
  'snapshotSerializers': [
    '<rootDir>/node_modules/jest-serializer-vue'
  ],
  'collectCoverageFrom': [ // 代码覆盖率考虑的文件
    'packages/**/*.{js,vue}',
    '!**/lib/**',
    '!**/ajax/**'
  ],
  'coverageDirectory': 'test/unit/coverage'
};