首页 > 解决方案 > 如何在 Jest 中模拟变量?

问题描述

Foo.jsx

import React from 'react';

export default (props) => {
  let {val} = props;

  if (val) {
    return 'ReactComponentFail';
  } else {
    return 'ReactComponent';
  }
};

Foo.test.js

import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Foo from './Foo';

Enzyme.configure({ adapter: new Adapter() });

let wrapper;

describe('foo test', () => {
  let props = { val: 0 }
  wrapper = shallow(<Foo {...props} />);

  test('component test', () => {
    expect(wrapper.text()).toEqual('ReactComponent');
  });
});

我怎么能嘲笑props?所以,我可以获得 100% 的代码覆盖率,任何帮助将不胜感激。我在谷歌上找不到任何关于如何模拟道具的信息。

标签: reactjsunit-testingjestjsenzyme

解决方案


创建模拟props并将其传递给您的 SFC。

例如

foo.jsx

import React from 'react';

export default (props) => {
  let { val } = props;

  if (val) {
    return 'ReactComponentFail';
  } else {
    return 'ReactComponent';
  }
};

foo.test.jsx

import React from 'react';
import { shallow } from 'enzyme';
import Foo from './foo';

describe('foo test', () => {
  test('should return ReactComponent', () => {
    let props = { val: 0 };
    let wrapper = shallow(<Foo {...props} />);
    expect(wrapper.text()).toEqual('ReactComponent');
  });
  test('should return ReactComponentFail', () => {
    let props = { val: 1 };
    let wrapper = shallow(<Foo {...props} />);
    expect(wrapper.text()).toEqual('ReactComponentFail');
  });
});

覆盖率 100% 的单元测试结果:

 PASS  stackoverflow/62694921/foo.test.jsx (10.41s)
  foo test
    ✓ should return ReactComponent (6ms)
    ✓ should return ReactComponentFail

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 foo.jsx  |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        11.845s, estimated 12s

推荐阅读