无法触发子组件上的请求

时间:2018-01-22 13:32:40

标签: javascript vue.js vuejs2 vue-test-utils moxios

我正在尝试添加一个可以检查vue-upload-component内发送的请求的测试。

单击“上传文件”按钮时发送请求,问题是我在模拟它时没有触发。

通常我会这样做(使用Jestvue-test-utils):

it('should stub request, basic case', (done) => {
        let wrapperDeep = mount(App, {});

        wrapperDeep.find('button').trigger('click'); // trigger request

        moxios.wait(() => {
            console.log(moxios.requests.mostRecent()); 
            // request was catched due to button click
            // ...
        });
    });

当我将axios调用绑定到@click事件时,它适用于一个简单的情况,但vue-upload-component的内部逻辑更复杂,可能因为这种方法不起作用:

 it('should stub request for file upload', (done) => {
        let wrapperDeep = mount(UploadForm, {});

        // simulating upload action by click doesn't work in this case:
        wrapperDeep.find('.upload-form__btn-upload').trigger('click'); 

        // simulate by subcomponent's update() method, also doesn't trigger anything
        wrapperDeep.find({ref: 'upload'}).vm.update({
            "fileObject": true,
            "size":       220288,
            "name":       "lazy_load.jpg",
            "type":       "image/jpeg",
            "active":     true,
            "error":      "",
            "success":    false,
            "putAction":  "/upload/put",
            "postAction": "/upload/post",
            "timeout":    0,
            "response":   {},
            "progress":   "0.00",
            "speed":      0,
            "data":       {"_csrf_token": "xxxxxx", "folder": undefined},
            "headers":    {"X-Csrf-Token": "xxxx"},
            "id":         "q6n9jgbr7g9",
            "blob":       "blob:http://localhost:8000/d2cba8e8-03b9-4ad9-aceb-907a1ca880d9",
            "thumb":      "blob:http://localhost:8000/d2cba8e8-03b9-4ad9-aceb-907a1ca880d9"
        }, { active: true });

        wrapperDeep.find({ref: 'upload'}).vm.$nextTick(() => {
            moxios.wait(() => {
                let request = moxios.requests.mostRecent(); // is undefined

                // returns "Cannot read property 'respondWith' of undefined", because no request was made
                // further code is not executed: 
                request.respondWith({
                    status:   200,
                    response: [
                        {id: 1, firstName: 'Fred', lastName: 'Flintstone'},
                        {id: 2, firstName: 'Wilma', lastName: 'Flintstone'}
                    ]
                }).then(function () {
                    console.log(wrapperDeep.find('.upload-form__item').html());
                    done();
                });
            });
        });
    });

0 个答案:

没有答案