JEST:无法访问道具中的功能

时间:2019-08-02 07:54:21

标签: reactjs redux jestjs enzyme

我正在尝试编写组件的测试用例,其中在componentDidMount()上我调用与bindActionCreators绑定的动作的两个函数。我面临一个奇怪的问题,当我使用浅层/山峰渲染来渲染组件时,在行上出现错误:

this.props.actions.getsomething()

Error : getSomething of Undefined

组件的安装。

componentDidmount () {
  this.props.actions.getSomething();
}

我对此的测试用例是:

it('it should dispatch action', () => {
        const actionsMock = { getSomething: jest.fn() };
        const localWrapper = shallow(<Componentes actions={ actionsMock } />);
        const instance = localWrapper.instance();
        instance.componentDidMount();
        expect(actionsMock.getSomething).toHaveBeenCalled();
    });

在这里,当我在componentDidMount()中放入一些console.logs时,我很想看到this.props.actions出现为:

{ getSomething:
         { [Function: mockConstructor]
           _isMockFunction: true,
           getMockImplementation: [Function],
           mock: [Getter/Setter],
           mockClear: [Function],
           mockReset: [Function],
           mockRestore: [Function],
           mockReturnValueOnce: [Function],
           mockResolvedValueOnce: [Function],
           mockRejectedValueOnce: [Function],
           mockReturnValue: [Function],
           mockResolvedValue: [Function],
           mockRejectedValue: [Function],
           mockImplementationOnce: [Function],
           mockImplementation: [Function],
           mockReturnThis: [Function],
           mockName: [Function],
           getMockName: [Function] },
}

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

您的代码对我来说很好:

index.jsx

import React, { Component } from 'react';

class SomeComponent extends Component {
  componentDidMount() {
    this.props.actions.getSomething();
  }
  render() {
    return <div></div>;
  }
}

export default SomeComponent;

index.spec.jsx

import React from 'react';
import SomeComponent from '.';
import { shallow } from 'enzyme';

describe('SomeComponent', () => {
  it('it should dispatch action', () => {
    const actionsMock = { getSomething: jest.fn() };
    const localWrapper = shallow(<SomeComponent actions={actionsMock} />);
    const instance = localWrapper.instance();
    instance.componentDidMount();
    expect(actionsMock.getSomething).toHaveBeenCalled();
  });
});

单元测试结果:

 PASS  src/stackoverflow/57322103/index.spec.jsx (12.116s)
  SomeComponent
    ✓ it should dispatch action (11ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        14.894s