【问题标题】:Is this the right way to to check a method using Jest / enzyme for React js这是检查使用 Jest / 酶 for React js 的方法的正确方法吗
【发布时间】:2019-01-30 03:38:28
【问题描述】:

目前我的测试通过了。我只想仔细检查这是否是检查方法的正确方法。如果不是,请尽可能更正

这是我目前所拥有的:file.test.js

 it ('handleChange: should call correctly ',() => {
   const wrapper = shallow(<Component {...baseProps } />);
   expect(wrapper).toMatchSnapshot();
   wrapper.setState({e: 'test'});
   expect(wrapper.instance().handleChange({target: {value : 'id'}}))
   expect(wrapper.instance().handleChange({target: {name : 'key'}}))
});

it('deleteAxis : should call correctly',() => {
  const wrapper = shallow(<Component {...baseProps } />);
  expect(wrapper).toMatchSnapshot();
  wrapper.setState({});
  expect(wrapper.instance().deleteAxis({ id:{} }))
})

这是主文件的一部分。文件.js

handleChange = (e) => {
  let localState = {}
  let key = e.target.name
  let value = e.target.value
  localState[key] = value
  localState['id'] = this.props.id
  this.props.addNewAxis(localState)
  this.setState(localState)
}

deleteAxis = () => {
  this.props.deleteAxisByID(this.props.id)
}

我希望这两种方法都经过测试并以正确的方式通过。我现在都在工作,但不确定它是否正确。 谢谢

【问题讨论】:

  • expect(wrapper.instance().handleChange({target: {value : 'id'}})) 您对此有何期待?您正在测试可以调用该方法,而不是它执行您期望它执行的任何操作

标签: reactjs unit-testing jestjs


【解决方案1】:

您可以将重复代码移动到 describe 块的 beforeEach 函数中,您可以检查并确保使用正确的值调用 addNewAxisdeleteNewAxisByID。最后,由于命名约定,您的 handleChange 函数有点混乱,请尽量保持一对一。

您可以将handleChange 函数更改为:

handleChange = e => {
  const { name, value } = e.target;
  const { id } = this.props;
  const newAxis = { id, [name]: value };    
  this.setState(newAxis, () => this.props.addNewAxis(newAxis)); //updates state first, then once updated, calls addNewAxis
}

然后你可以测试方法和后续的函数调用:

import React from 'react';
import { shallow } from 'enzyme';
import SomeComponent from './SomeComponent.js';

// jest mock functions (mocks this.props.func)
const addNewAxis = jest.fn();
const deleteAxisByID = jest.fn();

// defining this.props
const initialProps = {
  id: "abcd-1234-efgh-5678",
  addNewAxis,
  deleteAxisByID
}

describe('Some Component', () => {
  let wrapper;
  beforeEach(() => wrapper = shallow(<SomeComponent {...initialProps } />)); // before each test, shallow mount the Component

  // Option 1 - adding a spy, updating the instance and manually changing the input
  it('handles input changes and updates addNewAxis with a new value`, () => {
    const name = "Line 10";
    const value = 144;
    const { id } = initialProps;
    const newAxis = { id, [name]: value };

    const spy = jest.spyOn(wrapper.instance(), 'handleChange'); // spys an instance of Component's handleChange method
    wrapper.instance().forceUpdate(); // updates the instance to include the spy

    const input = wrapper.find('input'); // finds the input -- you can also find by className or some other identifying DOM element: wrapper.find('input.add-axis')
    input.simulate('change', { target: { value, name } }); // simulates an onChange event with values

    expect(spy).toBeCalled(); 
    expect(wrapper.state()).toContain(newAxis);
    expect(addNewAxis).toBeCalledWith(newAxis);
    spy.mockClear();
  });

  // Option 2 - calling the method directly
  it('handles input changes and updates addNewAxis with a new value`, () => {
    const name = "Line 10";
    const value = 144;
    const { id } = initialProps;
    const newAxis = { id, [name]: value };

    wrapper.instance().handleChange({ target: { value, name } }); // calls the instance handleChange method directly

    expect(wrapper.state()).toContain(newAxis);
    expect(addNewAxis).toHaveBeenCalledWith(newAxis);
  });

    // Same 2 options as above, up to your personal preference
  it('deletes an axis`, () => {
    const { id } = initialProps;

    wrapper.instance().deleteAxis();

    expect(deleteAxisByID).toHaveBeenCalledWith(id);
  });

});

【讨论】:

  • 为什么要监视实例方法,在使用选项 2 时,您仍然在下一行调用该方法?
  • 另外,您可以删除Option 2 上的spy = jest.spyOn(wrapper.instance(), 'deleteAxis');。现在您可以将间谍保留在Option 1 本地,而不是使用let
  • 我以前从未使用过间谍功能 - 检查我写的答案 - @mattcarlotta
  • 我很可能会坚持使用选项 2 - 我刚刚运行了代码 - 由于这一行 expect(wrapper.state()).toContain(newAxis); .预期对象:{"Line 10": 144, "id": "test Id"} 包含值:{"Line 10": 144, "id": "test Id"} 它们都是相同的,应该通过.但是当我评论这条线时,一切都运行良好
  • @mattcarlotta 有什么想法吗?
【解决方案2】:

这是我在编写单元测试文件时通常会做的事情

Describe(' FILE NAME', () => {

  let tree;
  let baseProps;
  let mockdefaultDataFromViewXML =  jest.fn().mockReturnValue({});
  let mockaddAxisList = jest.fn().mockReturnValue({});

beforeEach(() => {

baseProps = { 

 defaultDataFromViewXML : mockdefaultDataFromViewXML,
 addAxisList : mockaddAxisList,

【讨论】:

    猜你喜欢
    • 2016-05-10
    • 1970-01-01
    • 2012-05-11
    • 2018-12-31
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多