如何使用Jest /酶测试链接?

问题描述 投票:1回答:1

我有一个类似的React组件:

<A href="/products" onClick={(e) => this.onClick(tf)}>my link</A>

链接上附加了一个onClick处理程序,它将执行单独的功能,或者允许链接传播并重定向用户:

onClick(e, tf) {
    e.stopPropagation();
    if(tf){
        e.preventDefault();
        doSomethingElse();
    }
    // If execution gets here, then the link will follow through to /products
}

如何使用酶/笑话对此进行测试?

reactjs jestjs enzyme
1个回答
0
投票

这是单元测试解决方案:

index.jsx

import React, { Component } from 'react';

class Link extends Component {
  onClick(e, tf) {
    e.stopPropagation();
    if (tf) {
      e.preventDefault();
    }
  }
  render() {
    const { tf } = this.props;
    return (
      <a href="/products" onClick={(e) => this.onClick(e, tf)}>
        my link
      </a>
    );
  }
}

export default Link;

index.test.jsx

import Link from './index';
import React from 'react';
import { shallow } from 'enzyme';

describe('46213271', () => {
  it('should handle click, call stopPropagation and preventDefault', () => {
    const mProps = { tf: 'tf' };
    const wrapper = shallow(<Link {...mProps}></Link>);
    expect(wrapper.exists()).toBeTruthy();
    const mEvent = { stopPropagation: jest.fn(), preventDefault: jest.fn() };
    wrapper.simulate('click', mEvent);
    expect(mEvent.stopPropagation).toBeCalledTimes(1);
    expect(mEvent.preventDefault).toBeCalledTimes(1);
  });
  it('should handle click, call stopPropagation', () => {
    const mProps = { tf: '' };
    const wrapper = shallow(<Link {...mProps}></Link>);
    expect(wrapper.exists()).toBeTruthy();
    const mEvent = { stopPropagation: jest.fn(), preventDefault: jest.fn() };
    wrapper.simulate('click', mEvent);
    expect(mEvent.stopPropagation).toBeCalledTimes(1);
    expect(mEvent.preventDefault).not.toBeCalled();
  });
});

单元测试结果覆盖率100%:

 PASS  src/stackoverflow/46213271/index.test.jsx (17.292s)
  46213271
    ✓ should handle click, call stopPropagation and preventDefault (13ms)
    ✓ should handle click, call stopPropagation (2ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.jsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        19.864s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/46213271

© www.soinside.com 2019 - 2024. All rights reserved.