去抖动功能的 vue jest 单元测试

时间:2021-07-10 19:07:16

标签: vue.js unit-testing jestjs vue-jest

我想从我创建的 debounce 函数编写一个单元测试,但我似乎找不到解决方案。

这是代码:

    onSearchInputted: debounce(async function (e) {
        if (!this.search) {
          this.products = [...this.cachedProducts]
          return
        }

        try {
          const {data} = await this.$api.products.getAll((this.$helper.stringifyParams({
            ...this.params,
            name: this.search
          })))

          this.products = data.filter(v => !this.excludeItems.includes(v.id))

          this.products.forEach(v => {
            if (!this.cachedProducts.some(p => p.id === v.id)) {
              this.cachedProducts.push({...v})
            }
          })
        } catch (err) {
          this.products = []
        }
      }, 350)

到目前为止我尝试过的:

describe('debounce', () => {
      afterEach(() => {
        jest.restoreAllMocks();
        jest.resetAllMocks();
      });       
    jest.useFakeTimers();   
      test('execute just once', async () => {
          const { wrapper } = shallowMountFunc(AutocompleteProduct, {
                mocks: {
                  ...dataMocks
                },
                data() {
                  return {
                    ...dataOptions
                  }
                }
          })      

          var test = jest.fn();
          var debounced = _.debounce(test, 350);
         
          debounced();
         jest.runAllTimers()
         

          const vm = wrapper.vm;
          await vm.onSearchInputted()
      });
  });    

我在某处读到测试去抖动功能应该使用 jest 内置计时器,但还没有找到解决方案,我应该如何解决这个问题?

0 个答案:

没有答案