Laravel dusk: 使用 Dropzone.js 测试文件上传

Laravel dusk: test file upload with Dropzone.js

我正在使用 laravel 5.6Dusk 进行此特定测试。

我正在尝试在我的拖放区中断言文件上传。但是我的 Dropzone 是以我没有 file 输入元素的方式创建的。所以我不能使用 attach() 方法。

所以我尝试了以下方法

$file = new \Symfony\Component\HttpFoundation\File\UploadedFile(base_path() . '/tests/samples/Cylinder.stl', 'Cylinder.stl');

$response = $this->actingAs( $this->user )
                ->from( 'my-url' )
                ->post( route('attachments.store' ) , [
                    'file' => $file
                ]);

但错误包中包含此错误

"errors" => Illuminate\Support\ViewErrorBag {#1194             
  #bags: array:1 [                                             
    "default" => Illuminate\Support\MessageBag {#1189          
      #messages: array:1 [                                     
        "file" => array:1 [                                    
          0 => "The file failed to upload."                    
        ]                                                      
      ]                                                        
      #format: ":message"                                      
    }                                                          
  ]                                                            
}      

当然,当我手动执行时,这是有效的。

Dropzonejs 添加了一个带有特定“dz-hidden-input”class 的输入字段。 您可以在 html 页面底部找到它,可能就在 </body> 标签之前:

<input type="file" multiple="multiple" class="dz-hidden-input">

因此您可以通过附加方法告诉 Dusk 匹配那个确切的选择器:

$browser->attach('input.dz-hidden-input', storage_path('app/public/testing/test-file.jpg'));

如果您有一个显示文件名的拖放区预览和一个 'Remove file' 按钮,那么您可以像这样链接一些断言以确保该文件也可以被删除:

$browser->attach('input.dz-hidden-input', storage_path('app/public/testing/test-file.jpg'))
 ->assertSee('test-file.jpg')
 ->assertSeeLink('Remove file')
 ->clickLink('Remove file')
 ->assertDontSee('test-file.jpg');

正如另一个答案中提到的,该方法在于 dropzone.js 创建的虚拟输入字段。但是,如果您有多个单独的拖放区,这不是一个可行的解决方案,因为无法判断哪个输入字段是将文件附加到的正确输入字段。

最佳解决方案在于 hiddenInputContainer configuration value 放置区。指定一个可用于区分拖放区的值,例如包含您正在配置的拖放区的 div。

然后,您可以将文件附加到它(使用 Faker 作为生成文件的快捷方式):

$image = $faker->image('/tmp', 640, 480);
$browser->attach('#dropzone-image1 input.dz-hidden-input', $image);
$browser->attach('#dropzone-image2 input.dz-hidden-input', $image);