【问题标题】:Vuejs2 test http request on a form clickVuejs2在表单点击上测试http请求
【发布时间】:2019-03-09 07:43:27
【问题描述】:

在我的组件中

   methods:{
      ContactUs(){
            this.$http.post("/api/contact-us").then((res)=>{
               ///do new stuff
            },(err)=>{
               //do new stuff
            })
        },

    }

现在我想测试该方法是否有效

所以在我的测试中我有

 const wrapper = mount(ContactForm);

it("Contact us method should return a 200 response ", () => {
    wrapper.vm.ContactUs().then((res) => {
        expect(res.data).toEqual(res);
    })
    //await flushPromises();
});

但现在测试失败,错误指向this.$http.post...

如何测试上述功能

【问题讨论】:

  • 您应该将这样的逻辑排除在组件之外。将其放入函数或服务对象中并对其进行测试。
  • 错误信息是什么?

标签: javascript unit-testing vue.js jestjs


【解决方案1】:

如果你想将 .then() 链接到它,ContactUs 需要返回一个承诺。 this.$http.post 已经返回了一个 Promise,只需从 ContactUs 返回它的结果,你的测试就可以链接到它。

  ContactUs(){
        return this.$http.post("/api/contact-us").then((res)=>{
           ///do new stuff
        },(err)=>{
           //do new stuff
        })
    },

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多