如何使用Jest测试Axios剔除条件

egdjgwm8  于 2022-11-05  发布在  iOS
关注(0)|答案(2)|浏览(171)

我为组件中的一些Axios调用编写了一个单元测试。我验证了成功路径,其中调用成功解决,但我无法验证失败路径,其中调用被拒绝。我如何使用模拟来验证这一点?
下面是我的FetchImage.vue组件的一个片段:

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");
  });
});
cgyqldqp

cgyqldqp1#

您的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));
  });
});
pxiryf3j

pxiryf3j2#

您必须使用内置的jest方法拒绝该值。

describe('Invalid response', async () => {
  it('Invalid URL verfication', async () => {
    axios.get.mockRejectedValue(result);
  });
});

相关问题