使用jest-each进行动态数据测试

时间:2018-09-27 11:11:28

标签: reactjs testing jestjs

我正在研究React信用卡输入组件。

我需要使用jest-each按品牌类型测试信用卡号。

现有代码有效,但需要用jest-each替换动态数据 测试。

我认为它需要创建一个数组并将其放入visaNumbermastercardNumberamexNumberexpectedResult之类的变量中。

那么我该如何使用jest-each重构我的案子?

代码

import { mount } from 'enzyme';
import each from 'jest-each';
import * as React from 'react';
import { getCardTypeByValue } from '../../utils/formatter';
import CardNumber from './CardNumber';

const props = {
  placeholder: '',
  title: '',
};

// Valid Credit card numbers
const visaNumber = '4242 4242 4242 4242';
const mastercardNumber = '5555 5555 5555 4444';
const amexNumber = '3782 822463 10005';

function setup(ownProps = props) {
  return mount(<CardNumber {...ownProps} />);
}

describe('Card number component', () => {
  const wrapper = setup();

  it('Card number component should render properly', () => {
    expect(wrapper.instance() instanceof React.Component).toBe(true);
  });
});

describe('Get a card type by value', () => {
  it('Should get type for VISA', () => {
    const expectedResult = {
      maxCardNumberLength: 19,
      startPattern: /^4/,
      type: 'visa',
    };
    expect(getCardTypeByValue(visaNumber)).toEqual(expectedResult);
  });

  it('Should get type for MASTERCARD', () => {
    const expectedResult = {
      maxCardNumberLength: 16,
      startPattern: /^(5[1-5]|677189)|^(222[1-9]|2[3-6]\d{2}|27[0-1]\d|2720)/,
      type: 'mastercard',
    };
    expect(getCardTypeByValue(mastercardNumber)).toEqual(expectedResult);
  });

  it('Should get type for AMERICAN EXPRESS', () => {
    const expectedResult = {
      format: /(\d{1,4})(\d{1,6})?(\d{1,5})?/,
      maxCardNumberLength: 15,
      startPattern: /^3[47]/,
      type: 'amex',
    };
    expect(getCardTypeByValue(amexNumber)).toEqual(expectedResult);
  });
});

1 个答案:

答案 0 :(得分:2)

it.each([
        ['visa', 19, /^4/, visaNumber],
        ['mastercard', 16, /^(5[1-5]|677189)|^(222[1-9]|2[3-6]\d{2}|27[0-1]\d|2720)/, mastercardNumber],
    ])('Should get type for %s', (type, maxCardNumberLength, startPattern, number) => {
        const expectedResult = {
            maxCardNumberLength,
            startPattern,
            type,
        };
        expect(getCardTypeByValue(number)).toBe(expectedResult);
});