使用反应导航测试onClick

dan*_*son 1 reactjs jestjs react-native enzyme react-navigation

我正在将Jest与Enzyme一起使用,并且我拥有此组件,其中包括navigate方法调用:

export class LeadList extends React.Component {
  render() {
    const { navigate } = this.props.navigation;
    return (
      <List>
        {this.props.data.allLeads.map((lead, i) => {
          return (
            <ListItem
              key={i}
              onPress={() =>
                navigate('Details', lead.id)
              }
            />
            // ...
            </ListItem>
          )})}
      </List>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试测试它是否被正确调用,因此我将其组合在一起:

const testProps = props => ({
  data: {
    allLeads: [
      {id: 1, name: 'John Doe'},
      {id: 2, name: 'Jane Doe'}
    ],
    loading: false,
  },
  navigation: jest.fn((options, callback) => callback('Details', 1)),
  ...props,
})
describe('interactions', () => {
  let props
  let wrapper
  beforeEach(() => {
    props = testProps()
    wrapper = shallow(<LeadList {...props} />)
  })
  describe('clicking a lead', () => {
    beforeEach(() => {
      wrapper.find(ListItem).first().prop('onPress')
    })
    it('should call the navigation callback', () => {
      expect(props.navigation).toHaveBeenCalledTimes(1)
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

输出为:

Expected mock function to have been called one time, but it was called zero times.

解决这个问题的正确方法是什么?我需要使用间谍吗?

编辑:

当我像这样更改它时,我会得到相同的结果:

const testProps = props => ({
  // ...
  navigation: {navigate: jest.fn()},
  ...props,
})

it('should call the navigation callback', () => {
  expect(props.navigation.navigate).toHaveBeenCalledTimes(1)
})
Run Code Online (Sandbox Code Playgroud)

输出:

expect(jest.fn()).toHaveBeenCalledTimes(1)

Expected mock function to have been called one time, but it was called zero times.

  at Object.<anonymous> (__tests__/LeadList-test.js:48:35)
  at tryCallTwo (node_modules/promise/lib/core.js:45:5)
  at doResolve (node_modules/promise/lib/core.js:200:13)
  at new Promise (node_modules/promise/lib/core.js:66:3)
  at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
  at tryCallOne (node_modules/promise/lib/core.js:37:12)
  at node_modules/promise/lib/core.js:123:15
Run Code Online (Sandbox Code Playgroud)

Cor*_*rey 5

您将需要一个间谍来对此进行测试。这是一个示例测试,用于查找a上的ForgotPassword按钮LoginScreen并测试其导航到正确的屏幕。

test('Press Forgot Password Button', () => {
  const spy = jest.spyOn(navigation, 'navigate')
  const wrapper = shallow(
    <LoginScreen
      navigation={navigation}
      error={{}}
      onLogin={jest.fn()}
    />,
  )
  const forgotButton = wrapper.find('Button').at(0)
  forgotButton.props().onPress()

  expect(spy).toBeCalledWith('ForgotPassword')
})
Run Code Online (Sandbox Code Playgroud)