开玩笑酶如何测试onClick事件期间是否调用了组件内部的功能?

时间:2019-08-29 06:01:26

标签: javascript reactjs jestjs enzyme

当单击handleLogout按钮时,如何测试是否触发了data-test="logout"函数?

const NavBar = props => {
  const handleClick = (e, destination) => {
    e.preventDefault();
    props.history.push(`/${destination || ""}`);
  };

  // Test when data-test="logout" is clicked, handleLogout is called.
  const loginFormat =
    Object.keys(props.userDetails).length === 0 ? (
      <Fragment>
        <button onClick={e => handleClick(e, "login")}>Login</button>
        <button onClick={e => handleClick(e, "register")}>Register</button>
      </Fragment>
    ) : (
      // This button
      <button data-test="logout" onClick={e => handleLogout(e)}>
        Logout
      </button>
    );

  const handleLogout = e => {
    e.preventDefault();
    props.logoutUser();
    handleClick(e);
  };

  return (
    <header className="NavBar">
      <h2>PalettePicker</h2>
      <form className="navbar-form">{loginFormat}</form>
    </header>
  );
};

我当前的尝试:

  let mockUserDetails = { username: "steve", id: 123 };
  beforeEach(() => {
    wrapper = shallow(
      <NavBar
        userDetails={mockUserDetails}
        history={historyMock}
      />
    );
  });

  it("should invoke the handleLogout function when logout is clicked", () => {
    const mock = jest.spyOn(wrapper, "handleLogout");
    const button = wrapper.find('[data-test="logout"]');
    // console.log(button.debug());
    button.simulate("click", { preventDefault() {} });
  });

我收到以下错误消息:Cannot spy the handleLogout property because it is not a function; undefined given instead,所以我什至无法达到期望值,因为spyOn抛出了错误...任何想法吗?

2 个答案:

答案 0 :(得分:0)

请参阅此帖子Testing React Functional Component with Hooks using Jest。它可能与您的问题没有直接关系,但是您不应该测试是否已调用该方法,但是像接受的答案一样,您应该测试此方法引起的副作用。代码的问题还在于您正在使用功能组件,而run-ios函数不是NavBar的属性,因此您无权访问它。

答案 1 :(得分:0)

您不能窥探 handlelogout 函数,因为它是在函数作用域中定义的。这是私人

为了测试 handlelogout 函数,我们需要模拟 logout 按钮上的点击事件,将模拟事件对象传递给事件处理程序。另外,还得把logouUser方法传给组件,最后检查历史的路径名是否被预期的路径/改变了。

使用 createMemoryHistory 函数创建具有初始历史堆栈 /home 的内存历史。这意味着我们已登录的用户当前位于 /home 以获取测试用例。

例如

NavBar.jsx

import React, { Fragment } from 'react';

export const NavBar = (props) => {
  const handleClick = (e, destination) => {
    e.preventDefault();
    props.history.push(`/${destination || ''}`);
  };

  const loginFormat =
    Object.keys(props.userDetails).length === 0 ? (
      <Fragment>
        <button onClick={(e) => handleClick(e, 'login')}>Login</button>
        <button onClick={(e) => handleClick(e, 'register')}>Register</button>
      </Fragment>
    ) : (
      // This button
      <button data-test="logout" onClick={(e) => handleLogout(e)}>
        Logout
      </button>
    );

  const handleLogout = (e) => {
    e.preventDefault();
    props.logoutUser();
    handleClick(e);
  };

  return (
    <header className="NavBar">
      <h2>PalettePicker</h2>
      <form className="navbar-form">{loginFormat}</form>
    </header>
  );
};

NavBar.test.jsx

import { shallow } from 'enzyme';
import React from 'react';
import { NavBar } from './NavBar';
import { createMemoryHistory } from 'history';

describe('57703870', () => {
  it('should invoke the handleLogout function when logout is clicked', () => {
    const historyMock = createMemoryHistory({ initialEntries: ['/home'] });
    const props = {
      logoutUser: jest.fn(),
      userDetails: { username: 'steve', id: 123 },
      history: historyMock,
    };
    const wrapper = shallow(<NavBar {...props} />);
    expect(props.history.location.pathname).toEqual('/home');
    const button = wrapper.find('[data-test="logout"]');
    const mEvent = { preventDefault: jest.fn() };
    button.simulate('click', mEvent);
    expect(mEvent.preventDefault).toBeCalledTimes(2);
    expect(props.logoutUser).toBeCalledTimes(1);
    expect(props.history.location.pathname).toEqual('/');
  });
});

测试结果:

 PASS  examples/57703870/NavBar.test.jsx (8.534 s)
  57703870
    ✓ should invoke the handleLogout function when logout is clicked (9 ms)

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |   86.67 |       75 |   66.67 |   85.71 |                   
 NavBar.jsx |   86.67 |       75 |   66.67 |   85.71 | 12-13             
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.63 s