【问题标题】:Testing inner logic of method using vue-test-utils with Jest使用 vue-test-utils 和 Jest 测试方法的内部逻辑
【发布时间】:2020-09-01 05:47:41
【问题描述】:

如何测试以下方法的内部逻辑?

例如:

async method () {
  this.isLoading = true;
  await this.GET_OFFERS();
  this.isLoading = false;

  this.router.push("/somewhere");
}

所以我有了切换isLoading、调用动作并在某处路由的方法。我如何确定isLoading 已正确切换(在操作调用之前为true,之后为false)?

【问题讨论】:

    标签: javascript unit-testing vue.js frontend vue-test-utils


    【解决方案1】:

    您必须将 this.isLoading 行提取到新方法 setLoading() 中并检查它是否被调用。

    【讨论】:

    • 这真的只有一种方式吗?开玩笑(或一般的测试)模式是为了阻塞代码?
    • 我不确定你的意思是什么,但你无法分析你正在测试的函数的执行方式。只有通过调用其他函数来检查它是否做某事。实际上,如果您想让您的函数非常适合测试目的,您必须将函数内部使用的数据与外部数据分开。所以它可以更纯粹。您会在代码沙箱上创建一个测试沙箱,并给我们一个链接吗?
    【解决方案2】:

    shallowMount/mount 的第二个参数是mounting options,可用于在安装时覆盖组件的数据道具。这让您可以传入一个模拟isLoading 数据属性的setter,然后您可以验证该属性在被测方法中是否被修改:

    it('sets isLoading', () => {
      const isLoadingSetter = jest.fn()
    
      const wrapper = shallowMount(MyComponent, {
        data() {
          return {
            // This setter is called for `this.isLoading = value` in the component.
            set isLoading(value) {
              isLoadingSetter(value)
            }
          }
        }
      })
    
    
      //...
    })
    

    然后,您可以使用toHaveBeenCalledTimes()isLoadingSetter.mock.calls[] 来检查对模拟设置器的每次调用的参数。而且由于您想测试async 方法的效果,您必须在进行任何断言之前await 方法调用:

    it('sets isLoading', async () => {
      //...
    
      await wrapper.vm.method()
    
      expect(isLoadingSetter).toHaveBeenCalledTimes(2)
      expect(isLoadingSetter.mock.calls.[0][0]).toBe(true)
      expect(isLoadingSetter.mock.calls.[1][0]).toBe(false)
    })
    

    如果您还想验证是否调用了GET_OFFERS(),您可以在组件的方法安装之前使用jest.spyOn()

    it('gets offers', async () => {
      const getOfferSpy = jest.spyOn(MyComponent.methods, 'GET_OFFERS')
      const wrapper = shallowMount(MyComponent, /*...*/)
      await wrapper.vm.method()
      expect(getOfferSpy).toHaveBeenCalledTimes(1)
    })
    

    【讨论】:

      猜你喜欢
      • 2018-09-28
      • 2019-05-28
      • 2018-08-06
      • 2020-02-13
      • 2019-09-26
      • 2019-10-24
      • 2019-04-19
      • 2018-09-01
      • 2020-11-25
      相关资源
      最近更新 更多