React Jest酶-无法获得简单的按钮单击测试以通过

时间:2018-11-18 09:50:34

标签: reactjs unit-testing jestjs enzyme

我使用create-react-app引导了这个小项目,然后弹出,以便可以检查package.json。根据研究,我安装了酶和react-16适配器。我包括了package.json,以防万一。

我已经尝试了下面所有三个示例,每个示例实际上都单击了按钮,但是模拟中的期望都失败了。昨天迷失了整整一天,试图找出原因。我在做什么错或配置错误?

按钮组件:

import React from 'react'

class Button extends React.Component {

  handleClick = (arg) => {
    console.log('handleClick', arg)    
  }

  render() {
    return (
      <button type="button" onClick={this.handleClick}>
        Click Me
      </button>
    )
  }

}

测试:

import React from 'react'                                              
import Button from '../components/button'                              
import {shallow, configure} from 'enzyme';                             
import Adapter from 'enzyme-adapter-react-16';                         

configure({ adapter: new Adapter() });                                 

test('onClick called', () => {
  const wrapper = shallow(<Button />)
  wrapper.instance().onClick = jest.fn()
  wrapper.update()
  wrapper.instance().handleClick('junk')
  expect(wrapper.instance().onClick).toBeCalledWith('junk')
})

test('onClick called', () => {
  const mockOnClick = jest.fn();
  const wrapper = shallow(<Button onClick={mockOnClick} />)
  wrapper.find('button').simulate('click', 'junk')
  expect(mockOnClick.mock.calls.length).toEqual(1)
})

test('onClick called', () => {
  const mockOnClick = jest.fn()
  const wrapper = shallow(<Button onClick={mockOnClick}/>)
  wrapper.find('button').at(0).simulate('click', 'junk')
  expect(mockOnClick).toHaveBeenCalled()
})

测试控制台(首次测试)

console.log src/components/button.js:6
  handleClick junk

● onClick called

expect(jest.fn()).toBeCalledWith(expected)

Expected mock function to have been called with:
  ["junk"]
But it was not called.
  26 |   wrapper.update()
  27 |   wrapper.instance().handleClick('junk')
> 28 |   expect(wrapper.instance().onClick).toBeCalledWith('junk')
     |                                      ^
  29 | })
  30 |
  31 | // test('onClick called', () => {

  at Object.toBeCalledWith (src/__tests__/button-test.js:28:38)

测试控制台(第二项测试)

console.log src/components/button.js:6
  handleClick junk

● onClick called

expect(received).toEqual(expected)

Expected value to equal:
  1
Received:
  0
  33 |   const wrapper = shallow(<Button onClick={mockOnClick} />)
  34 |   wrapper.find('button').simulate('click', 'junk')
> 35 |   expect(mockOnClick.mock.calls.length).toEqual(1)
     |                                         ^
  36 | })
  37 |
  38 | // test('onClick called', () => {

  at Object.toEqual (src/__tests__/button-test.js:35:41)

测试控制台(第三项测试)

console.log src/components/button.js:6
  handleClick junk

● onClick called

expect(jest.fn()).toHaveBeenCalled()

Expected mock function to have been called, but it was not called.

  40 |   const wrapper = shallow(<Button onClick={mockOnClick}/>)
  41 |   wrapper.find('button').at(0).simulate('click', 'junk')    > 42 |   expect(mockOnClick).toHaveBeenCalled()
     |                       ^
  43 | })
  44 |
  45 | // test('onClick called', () => {

  at Object.toHaveBeenCalled (src/__tests__/button-test.js:42:23)

package.json

{
  "name": "react-testing-demo",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@babel/core": "7.1.0",
    "@svgr/webpack": "2.4.1",
    "babel-core": "7.0.0-bridge.0",
    "babel-eslint": "9.0.0",
    "babel-jest": "23.6.0",
    "babel-loader": "8.0.4",
    "babel-plugin-named-asset-import": "^0.2.3",
    "babel-preset-react-app": "^6.1.0",
    "bfj": "6.1.1",
    "case-sensitive-paths-webpack-plugin": "2.1.2",
    "chalk": "2.4.1",
    "css-loader": "1.0.0",
    "dotenv": "6.0.0",
    "dotenv-expand": "4.2.0",
    "enzyme": "^3.7.0",
    "enzyme-adapter-react-16": "^1.7.0",
    "eslint": "5.6.0",
    "eslint-config-react-app": "^3.0.5",
    "eslint-loader": "2.1.1",
    "eslint-plugin-flowtype": "2.50.1",
    "eslint-plugin-import": "2.14.0",
    "eslint-plugin-jsx-a11y": "6.1.2",
    "eslint-plugin-react": "7.11.1",
    "file-loader": "2.0.0",
    "fork-ts-checker-webpack-plugin-alt": "0.4.14",
    "fs-extra": "7.0.0",
    "html-webpack-plugin": "4.0.0-alpha.2",
    "identity-obj-proxy": "3.0.0",
    "jest": "23.6.0",
    "jest-pnp-resolver": "1.0.1",
    "jest-resolve": "23.6.0",
    "mini-css-extract-plugin": "0.4.3",
    "optimize-css-assets-webpack-plugin": "5.0.1",
    "pnp-webpack-plugin": "1.1.0",
    "postcss-flexbugs-fixes": "4.1.0",
    "postcss-loader": "3.0.0",
    "postcss-preset-env": "6.0.6",
    "postcss-safe-parser": "4.0.1",
    "react": "^16.6.3",
    "react-app-polyfill": "^0.1.3",
    "react-dev-utils": "^6.1.1",
    "react-dom": "^16.6.3",
    "react-test-renderer": "^16.6.3",
    "resolve": "1.8.1",
    "sass-loader": "7.1.0",
    "style-loader": "0.23.0",
    "terser-webpack-plugin": "1.1.0",
    "url-loader": "1.1.1",
    "webpack": "4.19.1",
    "webpack-dev-server": "3.1.9",
    "webpack-manifest-plugin": "2.0.4",
    "workbox-webpack-plugin": "3.6.3"
  },
  "scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx,ts,tsx}",
      "!src/**/*.d.ts"
    ],
    "resolver": "jest-pnp-resolver",
    "setupFiles": [
      "react-app-polyfill/jsdom"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
      "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,ts,tsx}"
    ],
    "testEnvironment": "jsdom",
    "testURL": "http://localhost",
    "transform": {
      "^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$",
      "^.+\\.module\\.(css|sass|scss)$"
    ],
    "moduleNameMapper": {
      "^react-native$": "react-native-web",
      "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "web.ts",
      "ts",
      "web.tsx",
      "tsx",
      "json",
      "web.jsx",
      "jsx",
      "node"
    ]
  },
  "babel": {
    "presets": [
      "react-app"
    ]
  }
}

1 个答案:

答案 0 :(得分:2)

该按钮的onclick处理程序设置为this.handleClick。尝试更改此内容以在事实发生后更改此内容是徒劳的

<button type="button" onClick={this.handleClick}>
  Click Me
</button>

第一个测试变体模拟onClick组件的Button方法;这不是Button组件的已定义方法。

// 1.
test('onClick called', () => {
  const wrapper = shallow(<Button />)
  wrapper.instance().onClick = jest.fn()
  wrapper.update()
  wrapper.instance().handleClick('junk')
  expect(wrapper.instance().onClick).toBeCalledWith('junk')
})

第二个和第三个变体将onClick道具转发到Button组件; Button组件不会公开onClick属性。

//2.
test('onClick called', () => {
  const mockOnClick = jest.fn();
  const wrapper = shallow(<Button onClick={mockOnClick} />)
  wrapper.find('button').simulate('click', 'junk')
  expect(mockOnClick.mock.calls.length).toEqual(1)
})

//3.
test('onClick called', () => {
  const mockOnClick = jest.fn()
  const wrapper = shallow(<Button onClick={mockOnClick}/>)
  wrapper.find('button').at(0).simulate('click', 'junk')
  expect(mockOnClick).toHaveBeenCalled()
})

由于您要测试单击按钮时是否调用handleClick,因此可以在闭包中调用this.handleClick

这使得在调用onclick处理程序时,它将在this.handleClick中调用该方法。

<button type="button" onClick={evt => this.handleClick(evt)}>
  Click Me
</button>

第一个测试变体适用于上述更改。

当暴露onClick组件中的Button属性时,其余测试变体将成功运行。

class Button extends React.Component {
  handleClick = (arg) => {
    this.props.onClick(arg);
    console.log('handleClick', arg)    
  }
  //...
}
Button.propTypes = {
  onClick: PropTypes.func.isRequired
}