首页 > 解决方案 > 异步/等待,没有达到下一个功能

问题描述

我有这个代码:

const handleButton = React.useCallback(async () => {
    try {
      await client.clearStore();
      navigation.push('screen');
    } catch (e) {
      logger.error('error', e);
    }
  }, []);

我正在测试nagivationto screen,但await我无法执行或到达navigation.push(). 如果我删除awaitonclient.clearStore一切正常,但行为可能与预期不同(我需要先 clearStore 然后导航)。

任何想法?

编辑:

我的测试是这样的:

import { useApolloClient } from '@apollo/react-hooks';
// After imports
jest.mock('@apollo/react-hooks');

// In describe:
describe('text', () => {
  beforeEach(async () => {
    // @ts-ignore
    moment.mockClear();
    useApolloClient.mockClear();
  });

  // My test:
    it.only('should redirects to MyComponent when button is pressed', async () => {
    const apolloClient = {
      clearStore: jest.fn()
    };
    useApolloClient.mockImplementation(() => apolloClient);

    apolloClient.clearStore
      .mockReturnValueOnce(
        Promise.resolve('foo')
      );

    moment.mockImplementation(
      (args: moment.MomentInput) =>
        jest.requireActual('moment')(args || '2020-07-30T20:00:00.000Z')
    );

    const navigation = {
      push: jest.fn()
    };

    const rendered = render(
      <MyComponent
        paymentGatewayCode='khipu'
        allowToPay={true}
        expiresDate={'2020-07-30T20:00:00.000Z'}
        navigation={navigation}
      />
    );

    const button = rendered.getByTestId('button');

    fireEvent.press(button);
    console.log('navigation.push.mock.calls', navigation.push.mock.calls);
    expect(navigation.push.mock.calls.length).toBe(1);
    expect(navigation.push.mock.calls[0]).toEqual(['MyComponent']);
  });

我在运行测试时得到了这个:

在此处输入图像描述

标签: javascriptreact-nativeasync-await

解决方案


推荐阅读