如何使用Jest测试Axios拒绝条件

时间:2019-05-12 22:15:10

标签: vue.js promise vuejs2 jestjs axios

我为组件中的一些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;
    });
  }
}

以及我对呼叫何时拒绝(针对无效网址)的测试:

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

1 个答案:

答案 0 :(得分:0)

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