javascript - 如何使用 Enzyme/Jest 测试 ComponentWillMount 中的逻辑

标签 javascript reactjs jestjs enzyme

我是用 enzyme /Jest 进行 react 单元测试的初学者, 我想在 componentWillMount 方法中测试我的逻辑。 我想根据我的上下文对象测试重定向是否根据我的业务逻辑发生

class ActivateSF extends Component {
  constructor(props) {
    super(props);
    this.className = 'ActivateSF.js'
    this.state = {
      messages: null,
     }
  }

  render() {
    return (
      <SDPActivateInterstitialUI
        context={this.props.context}
        messages={this.state.messages}
      />
    );
  }

  componentWillMount() {
    let context = this.props.context

    if(!context.userInfo){      
      return this.callIdentify(context)
    }

    let externalLP = ExternalLandingPageUtil.getExternalLandingPageUrl(context);
if (externalLP) {
      window.location.replace(`${externalLP}`);
      return;
    }

    if (context.userInfo)
    {
      console.log("user identified prior to activation flow")

        if (UserInfoUtil.isSubsribedUser(context))
        {
           window.location = '/ac'
        }

        else
        {
            this.callPaymentProcess(context)
        }
    }

  }

最佳答案

您可以尝试 beforeEach 挂载,并在测试中调用 .unmount 并对其执行测试。

beforeEach(() => {
     const myComponent= mount(<MyComponent myprop1={...} />);
});


describe('<MyComponent/>', () => {    
  it('actually unmounts', () => {
     ...
     ...
     myComponent.unmount();
    ... Do unmount tests here
  });
});

直接来自 enzyme 文档的示例:https://airbnb.io/enzyme/docs/api/ShallowWrapper/unmount.html

import PropTypes from 'prop-types';
import sinon from 'sinon';

const spy = sinon.spy();

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.componentWillUnmount = spy;
  }

  render() {
    const { id } = this.props;
    return (
      <div className={id}>
        {id}
      </div>
    );
  }
}
Foo.propTypes = {
  id: PropTypes.string.isRequired,
};
const wrapper = shallow(<Foo id="foo" />);
expect(spy).to.have.property('callCount', 0);
wrapper.unmount();
expect(spy).to.have.property('callCount', 1);

关于javascript - 如何使用 Enzyme/Jest 测试 ComponentWillMount 中的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57628047/

相关文章:

JavaScript : can i automatically call a function many times even if it has not finished being executed?

javascript - 如何在 jQuery/javascript 中添加多个监听器?

node.js - 用 CoffeeScript jsx 开 Jest ?

Javascript 缩略图更改

javascript - 如何使用 Javascript 加载 CSS 文件?

reactjs - React 16.7 protected 路由

reactjs - React - ComponentDidMount 没有从 Redux 状态获取值

reactjs - React Hook useEffect 缺少依赖项 : 'list'

typescript - 如何使用 jest 测试 Apollo Server 订阅?

javascript - Jest 和 enzyme 有什么区别?