Тестирование вызовов функций внутри callback с помощью jest - React-native - - PullRequest
1 голос
/ 10 февраля 2020

Я тестирую поведение функции с успешным вызовом API, мне удалось смоделировать ответ выборки, но функция внутри then обратного вызова не вызывается, даже если console.log, показывающий, что функция идет внутри обратный вызов.

Мой тест не пройден здесь:

enter image description here

Вот функция, которую я тестирую:


tryUserLogin() {
    this.setState({loading: true});
    const randomPassword = Math.random()
      .toString(36)
      .slice(-8);
    const email = this.state.inputEmail;
    const name = this.state.inputName;
    const formData = new FormData();
    formData.append('email', email);
    formData.append('name', name);
    formData.append('password', randomPassword);
    const query = Util.urlForAddUser();
    fetch(query, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data',
      },
      body: formData,
    })
      .then(response => response.json())
      .then(responseJson => {
        if (responseJson.code === 200) {
          firebase.analytics().logEvent('userSuccessfulLogIn', {
            userId: responseJson.response.id,
          });
          const userData = responseJson.response;
          console.log('userData',userData) // <==== i can see this in console
          this.storeUserData(userData, name);
          this.setState({loading: false});
          this.handleModalVisibility();
          this.props.handelAddComment();
          console.log('finish')
        } else {
          Alert.alert(
            this.props.t('common:title_error'),
            this.props.t('common:error'),
          );
          this.setState({loading: false});
        }
      })
      .catch(error => {
        firebase.crashlytics().log(
          `error tryUserLogin 
             LoginModal===>> ${error.message}`,
        );
        Alert.alert(
          this.props.t('common:title_error'),
          this.props.t('common:error'),
        );
        this.setState({loading: false});
      });
  }

А вот и тест:

it('testing tryUserLogin code 200 case', async () => {
    global.FormData = require('FormData');
    global.fetch = jest.fn();
    const userData = {
      code: 200,
      response: {
        id: 1,
        email: 'test+1234567890@t.com',
      },
    };
    const name = 'test';
    const email = 'test@t.com';
    const spyStoreUserData = jest.spyOn(instance, 'storeUserData');
    const spyHandelModalVisibility = jest.spyOn(
      instance,
      'handleModalVisibility',
    );
    fetch.mockImplementation(() => {
      return Promise.resolve({
        status: 200,
        json: () => {
          return Promise.resolve({
            ...userData,
          });
        },
      });
    });
    instance.setState({inputName: name});
    instance.setState({inputEmail: email});
    await instance.tryUserLogin();
    expect(spyStoreUserData).toBeCalledWith(userData.response, name);
    expect(fetch.mock.calls[0][0]).toBe('testQuery');
    expect(instance.state.loading).toBe(false);
    expect(spyHandelModalVisibility).toBeCalled();
    expect(mockHandelAddComment).toBeCalled();
  });
...