【问题标题】:How to test Axios reject condition using Jest如何使用 Jest 测试 Axios 拒绝条件
【发布时间】:2019-09-29 21:57:47
【问题描述】:

我为我的组件中的一些 Axios 调用编写了一个单元测试。我验证了呼叫成功解决的成功路径,但我无法验证呼叫拒绝的失败路径。如何使用模拟来验证这一点?

这是我的FetchImage.vue 组件的 sn-p:

methods: {
  preparedFetch() {
    axios.get(this.imageurl).then(result => {
      this.imageInformation.title = result.data.title;
      this.imageInformation.copyright = result.data.copyright;
      this.imageInformation.detailExplanation = result.data.explanation;
      this.imageInformation.date = result.data.date;
      this.imageInformation.urlinfo = result.data.url;
      this.resultArrived = true;
      this.$emit('imagefetched',this.imageInformation);
    })
    .catch( error => {
      this.errorMessage = "Information not found";
      this.resultArrived = true;
    });
  }
}

以及我对呼叫拒绝时的测试(对于无效的 URL):

describe('Invalid response',async () => {
  beforeEach(() => {
    axios.get.mockClear();
    axios.get.mockReturnValue(Promise.reject({}));
  });
  it('Invalid URL verfication', async () => {
    // Given
    const result = {
        errorMessage : "Information not found",
        resultArrived : true,
        fetchStatus : true
    };
    // Fetch the error result
    axios.get.mockReturnValue(Promise.resolve(result));
    const fetchwrapper = mount(FetchImage);
    fetchwrapper.vm.imageurl = "https://invalid.request.gov";
    fetchwrapper.vm.preparedFetch();
    await fetchwrapper.vm.$nextTick();
    // Validate the result
    expect(axios.get).not.toHaveBeenCalledWith('https://api.nasa.gov/planetary/apod?api_key=vME6LAMD7IhEiy7rDmjfIaG6MhiKbu1MNIqxtqd1');
    expect(axios.get).toHaveBeenCalledWith("https://invalid.request.gov");
    expect(axios.get).toHaveBeenCalledTimes(1);
    expect(fetchwrapper.vm.errorMessage.length).not.toEqual(0);
    expect(fetchwrapper.vm.errorMessage).toBe("Information not found");
  });
});

【问题讨论】:

    标签: vue.js promise vuejs2 jestjs axios


    【解决方案1】:

    您的 catch 块没有运行,因为模拟返回值使用的是 Promise.resolve(),而它实际上应该是 Promise.reject():

    describe('Invalid response',async () => {
      it('Invalid URL verfication', async () => {
        // axios.get.mockReturnValue(Promise.resolve(result)); // DON'T DO THIS
        axios.get.mockReturnValue(Promise.reject(result));
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2018-11-22
      • 2020-11-24
      • 2021-06-04
      • 2018-08-20
      • 2019-04-28
      • 2017-12-14
      • 2020-11-21
      • 2021-05-04
      • 2022-01-23
      相关资源
      最近更新 更多