簡體   English   中英

如何在解決承諾之前正確地讓 jest axios 模擬等待

[英]How to properly have jest axios mock wait before resolving promise

我有一個這樣的功能:

join(): void {
    this.working.value = true;
    if (this.info.value) {
      axios.get('/url')
        .then((result: ResultStatus) => {
          this.result = result;
        })
        .catch((reason: AxiosError) => {
          this.showError(AjaxParseError(reason));
        })
        .finally(() => {
          this.working.value = false;
        });
    }
  }

我想為此編寫一些單元測試。 我要編寫的第一個單元測試是測試 'this. Saving' 是否設置為 true,以便確保我的 UI 具有可用於顯示加載指示器的值。

但是,當我使用 jest 模擬 axios 時,jest 會立即解決 axios 承諾,並且我沒有機會測試在調用 then/finally 塊之前會發生什么。 這是我的單元測試代碼的樣子:

import axios from 'axios';
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;

import successResponse from './__json__/LeagueJoinInfoSuccess.json';

describe('constructor:', () => {
    let vm: classUnderTest;
    beforeEach(() => {
      vm = new classUnderTest();
      mockedAxios.get.mockResolvedValue({ data: successResponse }); // set up the response
      vm.join(); // the function under test
    });
    it('should set working true before calling the server to join', () => {
      expect(vm.working.value).toBeTruthy();
    });
    it('should set working false after calling the server responds', async () => {
      await flushPromises();
      expect(vm.working.value).toBeFalsy();
    });
});

第一個expect語句總是錯誤的,因為finally塊在我有機會執行await flushPromises()之前就運行了; 所以工作值總是假的。

有沒有一種方便的方法可以讓 jest 的 axios 模擬在解決其承諾之前等待?

更新:現在有一件非常奇怪的事情:如果我將 BeforeEach 的內容移動到每個測試中,那么它的行為方式就會像我希望的那樣。 我想我會開玩笑地打開一個問題並詢問他們發生了什么。

我有一個解決方案供您創建承諾作為響應,但是,我們不會在第一個測試用例中解決它以保持您測試加載狀態,然后在第二個測試中解決它,如下所示:

describe('constructor:', () => {

  let vm: classUnderTest;

  // Resolve function
  let resolveFn: (value?: unknown) => void

  beforeEach(() => {
    vm = new classUnderTest();

    const promise = new Promise(resolve => {
      // hold the resolve function to call in 2nd test
      resolveFn = resolve;
    });
    mockedAxios.get.mockImplementation(() => promise);

    vm.join(); // the function under test
  });

  it('should set working true before calling the server to join', () => {
    expect(vm.working.value).toBeTruthy();
  });

  it('should set working false after calling the server responds', async () => {
    // resolve the pending promise
    resolve({
      data: successResponse,
    });

    // I think you would wait the promise resolved
    await new Promise(resolve => setTimeout(resolve));

    expect(vm.working.value).toBeFalsy();
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM