前端单测,为什么不要测 “实现细节”?

lxf2023-05-05 19:09:01

前言

哈喽,大家好,我是海怪。

相信不少同学在写单测的时候,最大的困扰不是如何写测试代码,而是:“应该测什么?”,“要测多深入”,“哪些不该测”

最近在给 React 组件写单测的时候,发现了 Kent (React Testing Library 的贡献者之一)的 《Testing Implementation Details》 这篇文章,里面对 “为什么不要测代码实现细节?” 这个问题写得非常好,今天就把这篇文章也分享给大家。

翻译中会尽量用更地道的语言,这也意味着会给原文加一层 Buf,想看原文的可点击 这里。


开始

我以前用 enzyme 的时候,都会尽量避免使用某些 API,比如 shallow renderinginstance()state() 以及 find('ComponentName'),而且 Review 别人的 PR 的时候,也会跟他们说尽量别用这些 API。这样做的原因主要是因为这些 API 会测到很多代码的实现细节 (Implementation Details)。 然后,很多人又会问:为什么不要测 代码的实现细节(Implemantation Details) 呢?很简单:测试本身就很困难了,我们不应该再弄那么多规则来让测试变得更复杂。

为什么测试“实现细节”是不好的?

为什么测试实现细节是不好的呢?主要有两个原因:

  • 假错误(False Negative):重构的时候代码运行成功,但测试用例崩了
  • 假正确(False Positive):应用代码真的崩了的时候,然而测试用例又通过了

注:这里的测试是指:“确定软件是否工作”。如果测试通过,那么就是 Positive,代码能用。如果测试失败,则是 Negative,代码不可用。而这里的的 False 是指“不正确”,即不正确的测试结果

如果上面没看懂,没关系,下面我们一个一个来讲,先来看这个手风琴组件(Accordion):

// Accordion.js
import * as React from 'react'
import AccordionContents from './accordion-contents'

class Accordion extends React.Component {
  state = {openIndex: 0}
  setOpenIndex = openIndex => this.setState({openIndex})
  render() {
    const {openIndex} = this.state
    return (
      <div>
        {this.props.items.map((item, index) => (
          <>
            <button onClick={() => this.setOpenIndex(index)}>
              {item.title}
            </button>
            {index === openIndex ? (
              <AccordionContents>{item.contents}</AccordionContents>
            ) : null}
          </>
        ))}
      </div>
    )
  }
}

export default Accordion

看到这肯定有人会说:为什么还在用过时了的 Class Component 写法,而不是用 Function Component 写法呢?别急,继续往下看,你会发现一些很有意思的事(相信用过 Enzymes 的人应该能猜到会是什么)。

下面是一份测试代码,对上面 Accordion 组件里 “实现细节” 进行测试:

// __tests__/accordion.enzyme.js
import * as React from 'react'
// 为什么不用 shadow render,请看 https://kcd.im/shallow
import Enzyme, {mount} from 'enzyme'
import EnzymeAdapter from 'enzyme-adapter-react-16'
import Accordion from '../accordion'

// 设置 Enzymes 的 Adpater
Enzyme.configure({adapter: new EnzymeAdapter()})

test('setOpenIndex sets the open index state properly', () => {
  const wrapper = mount(<Accordion items={[]} />)
  expect(wrapper.state('openIndex')).toBe(0)
  wrapper.instance().setOpenIndex(1)
  expect(wrapper.state('openIndex')).toBe(1)
})

test('Accordion renders AccordionContents with the item contents', () => {
  const hats = {title: 'Favorite Hats', contents: 'Fedoras are classy'}
  const footware = {
    title: 'Favorite Footware',
    contents: 'Flipflops are the best',
  }
  const wrapper = mount(<Accordion items={[hats, footware]} />)
  expect(wrapper.find('AccordionContents').props().children).toBe(hats.contents)
})

相信有不少同学会用 Enzyme 写过上面类似的代码。好,现在让我们来搞点事情...

重构中的 “假错误”

我知道大多数人都不喜欢写测试,特别是写 UI 测试。原因千千万,但其中我听得最多的一个原因就是:大部分人会花特别多的时间来伺候这些测试代码(指测试实现细节的测试代码)。

每次我改点东西,测试都会崩!—— 心声

一旦测试代码写得不好,会严重拖垮你的开发效率。下面来看看这类的测试代码会产生怎样的问题。

假如说,现在我们要 将这个组件重构成可以展开多个 Item,而且这个改动只能改变代码的实现,不影响现有的组件行为。得到重构后代码是这样的:

class Accordion extends React.Component {
  state = {openIndexes: [0]}
  setOpenIndex = openIndex => this.setState({openIndexes: [openIndex]})
  render() {
    const {openIndexes} = this.state
    return (
      <div>
        {this.props.items.map((item, index) => (
          <>
            <button onClick={() => this.setOpenIndex(index)}>
              {item.title}
            </button>
            {openIndexes.includes(index) ? (
              <AccordionContents>{item.contents}</AccordionContents>
            ) : null}
          </>
        ))}
      </div>
    )
  }
}

上面将 openIndex 改成 openIndexes,让 Accordion 可以一次展示多个 AccordionContents。看起来非常完美,而且在 UI 真实的使用场景中也没任何问题,但当我们回去跑一下测试用例,