0

我想从我创建的 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 内置计时器,但还没有找到解决方案,我应该如何解决这个问题?

4

0 回答 0