亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Jest 中模擬類常量

在 Jest 中模擬類常量

慕桂英3389331 2022-11-11 14:19:15
假設我有以下this.MAX_LENGTH在構造函數中設置常量的組件。import PropTypes from 'prop-types';import React from 'react';class Input extends React.Component {  static propTypes = {    value: PropTypes.string.isRequired  };  constructor(props) {    super(props);    // An example constant    this.MAX_LENGTH = 1024;  }  render() {        return (      <label htmlFor="comment_body">        <textarea          className="comment-reply input-highlight-on-focus"          type="input"          name="comment[body]"          id="comment_body"          maxLength={this.MAX_LENGTH}          value={this.props.value} />      </label>    )  }}export default Input;該MAX_LENGTH常量用于設置的最大長度textarea。在我的 Jest 規范中,我想模擬 的值this.MAX_LENGTH,但我不確定如何設置該模擬。這是我的 Jest 測試的外觀(它使用chai并enzyme作為測試助手):it('renders the textarea', () => {  // Mock the constant here to set a custom value of 99  // ????  const wrapper = mount(<Input value={'foo'} />)  const textarea = wrapper.find('.comment-reply').first();  expect(textarea).to.have.attr('maxLength', '99');});我可以????用模擬常量的值來代替什么?我嘗試閱讀Jest 文檔中的ES6 Class Mocks,但它似乎是在模擬整個導入的類,我不確定它如何應用于單個常量。
查看完整描述

1 回答

?
月關寶盒

TA貢獻1772條經驗 獲得超5個贊

對常量使用實例屬性被認為是一種不好的做法;這就是靜態屬性的用途。這可以像Input.MAX_LENGTH = ...安裝組件之前一樣模擬:


class Input extends React.Component {

  static MAX_LENGTH = 1024;

  ...

}

中需要恢復原值afterEach。


或者至少使它成為只讀原型屬性。這可以像jest.spyOn(Input, 'MAX_LENGTH', 'get').mockReturnValue(...)安裝組件之前一樣模擬:


class Input extends React.Component {

  get MAX_LENGTH() { return 1024 };

  ...

}

沒有它,它需要在初始渲染后在組件實例上進行模擬:


const wrapper = mount(<Input value={'foo'} />)

wrapper.instance().MAX_LENGTH = ...;

wrapper.setProps({});

...


查看完整回答
反對 回復 2022-11-11
  • 1 回答
  • 0 關注
  • 125 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號