Как исправить нестабильный тест Jest при использовании Winston и Winston-ElasticSeacrh в React? - PullRequest
0 голосов
/ 31 января 2020

Я запускаю Jest-тест в React и установил winston. Когда я запускаю тест, я получаю разные результаты для каждого запуска. Некоторая информация из прогона:

>PASS  src/App.test.js
> PASS  src/Welcome.test.js
> PASS  src/Hide.test.js
> PASS  src/Dish.test.js
> PASS  src/Toggle.test.js
>(node:40016) UnhandledPromiseRejectionWarning: TypeError: Caught error after test environment >was torn down

>Cannot read property 'body' of null
>(node:40016) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error >originated either by throwing inside of an async function without a catch block, or by >rejecting a promise which was not handled with .catch(). To terminate the node process on >unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see >https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
>(node:40016) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the >future, promise rejections that are not handled will terminate the Node.js process with a non->zero exit code.
> FAIL  src/Counter.test.js
>  ● should increment the count
>
>    TypeError: require(...) is not a function>
>
>      at Object._lazyLoad [as existsTemplate] (node_modules/@elastic/elasticsearch/api/index.js:572:39)
>      at BulkWriter.ensureMappingTemplate (node_modules/winston->elasticsearch/bulk_writer.js:186:23)
>      at node_modules/winston-elasticsearch/bulk_writer.js:148:18
>
>Test Suites: 1 failed, 5 passed, 6 total
>Tests:       1 failed, 9 passed, 10 total
>Snapshots:   0 total
>Time:        12.208s
>Ran all test suites.

Мой компонент React, в котором я использую регистратор, выглядит следующим образом

"use strict"
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Welcome from './Welcome'
import Logger from './Logger'

class Hide extends Component {
    logger
   constructor(props) {
      super()
      this.logger = Logger.getLogger()
      this.logger.info('constructor')
   }



   componentDidMount() {   
      this.logger.info('componentDidMount')
   }

   componentWillUnMount () {  
       this.logger.info('componentWillUnMount')
    }

  componentDidCatch() { 
    this.logger.info('componentDidCatch')
   }



  componentDidUpdate() {  }





  state = {
    toggle: true
  }

  toggle = () => {
    this.setState({
      toggle: !this.state.toggle
    })
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <Welcome text="Welcome to Using Props" toggle={this.state.toggle} />
        </header>
        this.logger.info('render')
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
        {this.state.toggle &&
          <p>This should show and hide</p>
        }
        <button onClick={this.toggle}>Show / Hide</button>
      </div>
    );
  }
}

экспорт по умолчанию Скрыть;

Моя посылка json выглядит как

{
  "name": "hookstutorial",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-scripts": "3.3.0",
    "winston": "^3.2.1",
    "winston-elasticsearch": "^0.8.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "jest-fetch-mock": "^3.0.1"
  }
}

Мой файл журнала выглядит так

var winston = require('winston');
var Elasticsearch = require('winston-elasticsearch');
  var instance = null
  var logger
  var esTransportOpts = {
    level: 'info',
     clientOpts: { node: 'http://localhost:9200' },
     index: 'hookstutorial' 
    }

    class Logger { 

       constructor() {
            logger = winston.createLogger({
               transports: [
                   new Elasticsearch(esTransportOpts)
              ]
           })
        }

         static getLogger() { 
         if (instance == null)  { 
            instance =  new Logger()
          }
         return logger
       }
     } 
    export default Logger

Как мне исправить эту ошибку?

...