Тест на шутку / энзим не проходит из-за импортированного сервиса - PullRequest
0 голосов
/ 31 октября 2019

У меня есть шут-тест, который проверяет компонент, который визуализируется поверхностно:

import * as React from 'react';
import { shallow } from 'enzyme';

import MFASection from './MFASection';

test('molecules/MFASection mounts', () => {
    const component = shallow(<MFASection />);
    expect(component.exists()).toBe(true);
});

и где он терпит неудачу, находится здесь:

TypeError: Cannot read property 'then' of undefined
componentDidMount(): () => Promise<any> {
    > 22 |              return svc.getMe()
         |                     ^
      23 |                      .then((res) => {
      24 |                              this.setState({ enabledMFA: res.data.mfa_enabled });
      25 |                      });

в компоненте, svc - этобудучи импортированным и использованным в componentDidMount

import svc from 'constants/svc';

....
componentDidMount(): () => Promise<any> {
        return svc.getMe()
            .then((res) => {
                this.setState({ enabledMFA: res.data.mfa_enabled });
            });
    }

все остальное - просто пользовательский сервис, который я написал:

import Svc from '@spring/svc';

import { getOrCreateStore } from 'utils/redux/wrapper';

export default new Svc(process.env.AUTH_API_DOMAIN, getOrCreateStore());

Я не уверен, как пройти этот тест. Что-то мне не хватает в самом тесте?

1 Ответ

0 голосов
/ 14 ноября 2019

Вот два решения:

  • jest.spyOn

  • setImmediate

Например:

index.tsx:

import React, { Component } from 'react';
import svc from './contants/svc';

class MFASection extends Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {
      enabledMFA: true
    };
  }
  componentDidMount() {
    svc.getMe().then(res => {
      console.log(res);
      this.setState({ enabledMFA: res.data.mfa_enabled });
    });
  }
  render() {
    return <div>enabledMFA: {this.state.enabledMFA ? '1' : '2'}</div>;
  }
}

export default MFASection;

index.spec.tsx:

import React from 'react';
import { shallow } from 'enzyme';
import MFASection from '.';
import svc from './contants/svc';

describe('MFASection', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  test('molecules/MFASection mounts', done => {
    const mRepsonse = { data: { mfa_enabled: false } };
    let successHandler;
    const getMeSpy = jest.spyOn(svc, 'getMe').mockImplementation((): any => {
      const mThen = jest.fn().mockImplementationOnce((onfulfilled: any): any => {
        successHandler = onfulfilled;
      });
      return { then: mThen };
    });
    const wrapper = shallow(<MFASection></MFASection>);
    expect(wrapper.exists()).toBe(true);
    expect(wrapper.state('enabledMFA')).toBeTruthy();
    successHandler(mRepsonse);
    expect(wrapper.text()).toBe('enabledMFA: 2');
    expect(getMeSpy).toBeCalledTimes(1);
    done();
  });

  test('molecules/MFASection mounts - 2', done => {
    const mRepsonse = { data: { mfa_enabled: false } };
    const getMeSpy = jest.spyOn(svc, 'getMe').mockResolvedValueOnce(mRepsonse);
    const wrapper = shallow(<MFASection></MFASection>);
    expect(wrapper.exists()).toBe(true);
    expect(wrapper.state('enabledMFA')).toBeTruthy();
    setImmediate(() => {
      expect(wrapper.text()).toBe('enabledMFA: 2');
      done();
    });
    expect(getMeSpy).toBeCalledTimes(1);
  });
});

contants/svc.ts:

const getOrCreateStore = () => {};

class Svc {
  constructor(domain, getOrCreateStore) {}

  public async getMe() {
    return { data: { mfa_enabled: true } };
  }
}

export default new Svc(process.env.AUTH_API_DOMAIN, getOrCreateStore());

результат модульного теста сотчет о покрытии:

 PASS  src/stackoverflow/58648463/index.spec.tsx (5.062s)
  MFASection
    ✓ molecules/MFASection mounts (87ms)
    ✓ molecules/MFASection mounts - 2 (18ms)

  console.log src/stackoverflow/58648463/index.tsx:1573
    { data: { mfa_enabled: false } }

  console.log src/stackoverflow/58648463/index.tsx:1573
    { data: { mfa_enabled: false } }

------------------------|----------|----------|----------|----------|-------------------|
File                    |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
------------------------|----------|----------|----------|----------|-------------------|
All files               |    95.24 |      100 |    88.89 |    94.74 |                   |
 58648463-todo          |      100 |      100 |      100 |      100 |                   |
  index.tsx             |      100 |      100 |      100 |      100 |                   |
 58648463-todo/contants |    83.33 |      100 |       75 |    83.33 |                   |
  svc.ts                |    83.33 |      100 |       75 |    83.33 |                 7 |
------------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        6.965s, estimated 13s

Исходный код: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58648463

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...