0

我正在尝试为 Vue 编写一些单元测试,而不是每次都设置一个新的包装器,我想使用 beforeEach() 来自动处理它。当我运行调试器时,它会失败所有测试,然后为每个测试运行 beforeEach() 函数。

这是我的 .spec.js 文件。

import  {
  mount,
} from '@vue/test-utils';
import  QcAddressView from './address-view.vue';
const id = 'test_address-view';

describe('qc-address-view', () => {
  let wrapper = null

  beforeEach(() => {
    console.log("beforeEach executed!");
    wrapper = mount(QcAddressView, {
      id,
      address: {
          addrLine1: '111 Testerson Way',
          addrLine2: '',
          cityName: 'Olympia',
          stateCode: 'WA',
          zipCode: '98512',
          countyName: 'Thurston',
          countryName: 'United States of America',
      },
    })
  })

  test('sets up a valid address', () => {
    console.log('sets up a valid address');
    expect(wrapper.attributes('id')).toBe(id);
  })
});

控制台显示测试失败:

FAIL: qc-address-view
× sets up a valid address (72ms)
TypeError: Cannot read property 'addrLine1' of undefined
TypeError: Cannot read property 'attributes' of null

它无法读取属性,因为 beforeEach() 尚未设置对象。

然后它在测试之后而不是之前运行 beforeEach() :

console.log: beforeEach executed!

当我用三个测试尝试它时,每个测试都会失败,然后 console.log 会打印“beforeEach executed!” 三次。

如何让 beforeEach() 在每次测试之前运行,而不是每次测试?

4

2 回答 2

2

beforeEach 实际上是在您的测试之前运行。否则,wrappernull在你的测试中,你会得到一个不同的错误。

您会在测试看到控制台日志,因为Jest 缓冲了日志输出,并在测试结束时将其转储。您可以通过设置来避免缓冲useStderr。您可以通过以下方式执行此操作jest.config.js

module.exports = {
  useStderr: true,
}
于 2021-06-28T22:01:22.860 回答
0

答案是将idandaddress放入一个attrs对象中,因此:

wrapper = mount(QcAddressView, {
  attrs: {
    id,
    address: {
      addrLine1: '111 Testerson Way',
      addrLine2: '',
      cityName: 'Olympia',
      stateCode: 'WA',
      zipCode: '98512',
      countyName: 'Thurston',
      countryName: 'United States of America',
    },
  }
})
于 2021-06-28T21:31:30.687 回答