Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/458.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Jest单元测试-在正在测试的函数中修改的全局变量未定义_Javascript_Reactjs_Unit Testing_Testing_Jestjs - Fatal编程技术网

Javascript Jest单元测试-在正在测试的函数中修改的全局变量未定义

Javascript Jest单元测试-在正在测试的函数中修改的全局变量未定义,javascript,reactjs,unit-testing,testing,jestjs,Javascript,Reactjs,Unit Testing,Testing,Jestjs,我不太会开玩笑,并且尝试为tsx文件编写单元测试用例。我试图测试一个函数,它接受一个参数并将全局变量(x)的值设置为与传递的参数相等。当我运行测试时,我得到的值是未定义的。代码如下: .TSX文件 import { Component, Event, EventEmitter, Method, Prop } from '@stencil/core'; import { CountryLanguageSelectorModel } from './country-language-selecto

我不太会开玩笑,并且尝试为tsx文件编写单元测试用例。我试图测试一个函数,它接受一个参数并将全局变量(x)的值设置为与传递的参数相等。当我运行测试时,我得到的值是未定义的。代码如下:

.TSX文件

import { Component, Event, EventEmitter, Method, Prop } from '@stencil/core';

import { CountryLanguageSelectorModel } from './country-language-selector.model';

@Component({
  tag: 'dxp-country-language-selector',
  styleUrls: ['dxp-country-language-selector.css'],
  shadow: false
})
export class CountryLanguageSelector {
  @Prop({ mutable: true }) contentData: CountryLanguageSelectorModel;
  @Prop({ mutable: true }) contentPath = '../assets/mock.json';
  @Prop({ mutable: true }) modalView: boolean;
  @Prop({ mutable: true }) selectedCountry: string;
  @Prop({ mutable: true }) selectedLanguage: string;
  @Event() countrySelected: EventEmitter;
  @Event() languageSelected: EventEmitter;

  componentWillLoad () {
    this.getData(this.contentPath)
      .then(data => {
        this.contentData = data;
        this.selectedCountry = this.contentData.countryList[0];
        this.selectedLanguage = this.contentData.languageList[0];
      });
  }

  @Method()
  getData (contentPath: string): Promise<CountryLanguageSelectorModel> {
    if (contentPath) {
      return fetch(contentPath)
        .then((response: any) => {
          if (response.ok) {
            return response.json();
          } else {
            return Promise.resolve(null);
          }
        });
    } else {
      return Promise.resolve(this.contentData);
    }
  }

  countrySelectedHandler (selectedCountry) {
    this.selectedCountry = selectedCountry.target.value;
    this.countrySelected.emit(selectedCountry.target.value);
  }

  languageSelectedHandler (selectedLanguage) {
    this.selectedLanguage = selectedLanguage.target.value;
    this.languageSelected.emit(selectedLanguage.target.value);
  }

  render () {
    if (this.contentData) {
      return (
        <div>
          <div id="country-selector" class="country-selector primary-light" onClick={() => { this.modalView = true }}>
            <div class="wrapper">
              <p class="globe-wrapper"></p>
              <a href="#." class="clang-selector" role="button" aria-disabled="false"><span
                class="country">{this.selectedCountry}
                <span class="down-arrow"></span>
            </span><span class="lang small">{this.selectedLanguage}</span></a>
            </div>
          </div>
          { this.modalView ?
            <div class="modal main-section col-12 visible" id="modal">
              <div class="modal-dialog col-xl-8 col-lg-8 col-md-10 primary-light">
                <div class="modal-header">
                <span class="btn-close" id="closeBtn"
                      onClick={() => this.modalView = false}><span
                  class="icon icon-close"></span></span>
                </div>
                <div class="modal-body">
                  <p><a href="" aria-label="go to">
                    {/*<span class="mastercard-logo"></span>*/}
                    <img src={this.contentData.imageUrl}></img>
                  </a></p>
                  <h5>{this.contentData.title}</h5>
                  <p>{this.contentData.subtitle}</p>
                  <div id="country">
                    <div>Country</div>
                    <select title="Select your country" aria-label="Select your country"
                            onInput={event => this.countrySelectedHandler(event)}>
                      {this.contentData.countryList.map(country =>
                        <option>{country}</option>
                      )}
                    </select>
                  </div>
                  <p></p>
                  <div id="lang">
                    <div>Language</div>
                    <select title="Select your language" aria-label="Select your language"
                            onInput={event => this.languageSelectedHandler(event)}>
                      {this.contentData.languageList.map(language =>
                        <option>{language}</option>
                      )}
                    </select>
                  </div>
                </div>
                <div class="modal-footer">
                  <button class="btn btn-cta btn-brick" id="go-back"
                          onClick={() => this.modalView = false}>{this.contentData.buttonText}</button>
                </div>
              </div>
            </div> : '' }
        </div>
      )
    }
  }
}
======这是失败的===========

     import { TestWindow } from '@stencil/core/testing'

import { CountryLanguageSelector } from './dxp-country-language-selector'

let obj = new CountryLanguageSelector();
window.fetch = jest.fn().mockImplementation(contentPath => {
  if (contentPath === '../assets/mock.json') {
    return Promise.resolve({
      json: () => {
        return {
          'title': 'Select Country',
          'subtitle': 'Lorem Ipsum',
          'logoPath': '../images/icons/logo.svg',
          'countryList': ['India', 'USA', 'Australia'],
          'languageList': ['English', 'Hindi', 'French'],
          'buttonText': 'Go Back To Site'
        };
      }
    });
  } else {
    return Promise.resolve('error');
  }
});

describe('CountryLanguageSelector', () => {

  beforeEach(() => {
    obj = new CountryLanguageSelector();
  });
  // it('should set the passed argument as selected country', () => {
  //   let country = { target : { value: '' } } ;
  //   country.target.value = 'India';
  //   obj.languageSelectedHandler(country);
  //   expect(obj.selectedLanguage).toEqual('India');
  // });
});

====================================================

您发布的代码中没有全局变量。这个问题缺乏答案。没有你要测试的课程。测试失败是因为它的某些部分不能像你期望的那样工作。@estus我没有在这里发布整个文件。函数中的全局变量是
selectedCountry
,很容易理解。不需要整个文件,但问题应包含所有相关代码。问题包含所有必要的代码。单元测试的目的是孤立地测试功能。不需要整个代码或类。我同意它们需要单独测试。遗憾的是,无法解释为什么这个值没有这样定义。这是你的问题,不是吗?因为没有显示负责此行为的代码。没有设置
selectedLanguage
的代码。
     import { TestWindow } from '@stencil/core/testing'

import { CountryLanguageSelector } from './dxp-country-language-selector'

let obj = new CountryLanguageSelector();
window.fetch = jest.fn().mockImplementation(contentPath => {
  if (contentPath === '../assets/mock.json') {
    return Promise.resolve({
      json: () => {
        return {
          'title': 'Select Country',
          'subtitle': 'Lorem Ipsum',
          'logoPath': '../images/icons/logo.svg',
          'countryList': ['India', 'USA', 'Australia'],
          'languageList': ['English', 'Hindi', 'French'],
          'buttonText': 'Go Back To Site'
        };
      }
    });
  } else {
    return Promise.resolve('error');
  }
});

describe('CountryLanguageSelector', () => {

  beforeEach(() => {
    obj = new CountryLanguageSelector();
  });
  // it('should set the passed argument as selected country', () => {
  //   let country = { target : { value: '' } } ;
  //   country.target.value = 'India';
  //   obj.languageSelectedHandler(country);
  //   expect(obj.selectedLanguage).toEqual('India');
  // });
});