【问题标题】:Vue unit test: beforeEach() executing after all tests, not before each testVue单元测试: beforeEach() 在所有测试之后执行,而不是在每个测试之前执行
【发布时间】:2021-09-11 00:13:44
【问题描述】:

我正在尝试为 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() 在每次测试之前运行,而不是每次都运行?

【问题讨论】:

    标签: vue.js jestjs vue-test-utils


    【解决方案1】:

    beforeEach 在您的测试之前实际运行。否则,wrapper 在您的测试中将是 null,您会得到不同的错误。

    您会看到控制台记录了 在测试之后因为Jest buffers the log output,并在测试结束时转储它。您可以通过设置useStderr 来避免缓冲。您可以通过jest.config.js 执行此操作:

    module.exports = {
      useStderr: true,
    }
    

    【讨论】:

    • 在 useStderr 上不错。
    • 谢谢,这对了解很有帮助!
    【解决方案2】:

    答案是将idaddress 放入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',
        },
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      • 2023-04-11
      • 2019-07-19
      • 2013-01-24
      相关资源
      最近更新 更多