未调用window.history.back()-开玩笑的酶

时间:2019-02-04 19:18:18

标签: reactjs jestjs enzyme

我为以下内容编写了一个简单的单元测试。我是React JS测试的新手-尝试使用笑话和酶进行测试。

     render() {
  return (
    <div>
      <div className="not-found">
      <div className='_2'>WAS NOT FOUND</div>
            <div onClick={() => {window.history.back()}} className='not-found- 
 btn' href='/'>GO BACK</div>

      )        }      }

该文件看起来很简单,没有任何道具,并且运行测试时唯一没有覆盖的就是onClick。我如何测试onClick并确保测试100%覆盖。谢谢

 <div onClick={() => {window.history.back()}} className='not-found- 
 btn' href='/'>GO BACK</div>

file.test.js

  // jest mock functions (mocks this.props.func)
   const onClick =  jest.fn();
 // defining this.props
 const baseProps = {
  onClick,
}

describe(' Test', () => {
let wrapper;
let tree;

 beforeEach(() => wrapper = shallow(<Component{...baseProps } />));
// before each test, shallow mount the Component

it('should render correctly', () => {  
tree = renderer.create(<NotFound {...baseProps} />)
let treeJson = tree.toJSON()
expect(treeJson).toMatchSnapshot();
tree.unmount()
});

       it('calls onClick event ', () => {
  const mockOnClick = jest.fn();
 const wrapper = shallow(
    <NotFound onClick={mockOnClick} className='not-found-btn' />
  );
  const component = wrapper.shallow();
  component.find('GO BACK').simulate('click');
  expect(mockOnClick.mock.calls.length).toEqual(1);

2 个答案:

答案 0 :(得分:1)

window.history.back被调用,但是有一个延迟时间。我可以使用Promise使其工作:

const Component = ()=> (<div>
  <button onClick={()=> window.history.back()} className="btn btn-back">
    Back
  </button>
</div>)

Component.test.js

import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
     
const delayAction = (fn, time = 1000) =>
      new Promise((resolve) => {
        fn();
        setTimeout(() => {
          resolve();
        }, time);
      });

let container = null;

describe("App tests", () => {
  afterEach(() => {
    //unmount Component...
  });

  beforeEach(() => {
    //mount Component
  });

  it("should call history.back()", async (done) => {
    const btnBack = container.querySelector(".btn-back");
    await act(() =>
      delayAction(() => btnBack.dispatchEvent(new MouseEvent("click", { bubbles: true })))
    );
    // asserts..
    
    done();
  });

});

答案 1 :(得分:0)

我将避免使用window历史记录,而应将react-router-dom用于MPA。另外,您可以使用{{1}类(类似于PureComponent类,但不会更新Component来代替使用匿名函数) }类函数。

工作示例https://codesandbox.io/s/j3qo6ppxqy(此示例使用state,并且混合了methodreact-router-dom测试,请参见{{页面底部的1}}标签以运行测试并寻找integration文件夹以查看代码)

components / NotFound / notfound.js

unit

components / NotFound / __ tests __ / notfound.test.js (如here所述,如果需要,您也可以测试类方法)

tests