当Component.prototype返回未定义时,如何使用玩笑/酶对componentDidMount进行单元测试?

时间:2020-01-15 21:03:50

标签: reactjs unit-testing jestjs enzyme

我正在尝试编写一个简单的测试,以查看是否在下面的componentDidMount组件中调用了HomePage

class HomePage extends Component {
  state = {...}
  async componentDidMount(){
    // a couple of if conditions and an ajax request
  }
}

对于测试,我正在尝试以下操作,以查看是否调用了componentDidMount:

describe('<Homepage/>', () => {
  let props, store, mockStore, initialState

  beforeEach(() => {
    props = {
      getPoints: jest.fn(),
      estimatePoints: jest.fn()
    }
    initialState = {
      homeReducer: {
        profile: {}
      },
      pointsReducer: {
        score: {
          points: {}
        }
      }
    }

    mockStore = configureStore()
    store = mockStore(initialState)
  })

  it('should call the componentDidMount lifecycle method', () => {
    const spy = jest.spyOn(HomePage.prototype, 'componentDidMount')
    const wrapper = mount(
      <Provider store={store}>
        <HomePage {...props}/>
      </Provider>
    )
    expect(spy).toHaveBeenCalled()
    wrapper.unmount()
  })
})

我遇到的错误是Cannot spyOn on a primitive value; undefined given。我也尝试过使用shallowwrapper.instance(),但都没有运气。在这种情况下,测试componentDidMount的正确方法是什么?

0 个答案:

没有答案