axios 如何使用mocking来测试jest上传文件

ldxq2e6h  于 2022-12-23  发布在  iOS
关注(0)|答案(1)|浏览(218)

我正在用nuxt js和jest开发一个系统,其中我想上传一张图片。
下面是我的html代码:

<input
    id="photo"
    ref="photo"
    type="file"
    name=""
    class="form-control d-flex"
    @change="uploadPhoto"
>

下面是我在nuxt js中的uploadPhoto函数:

uploadPhoto () {
    const file = this.$refs.photo.files[0]
    // upload photo
    const formData = new FormData()
    formData.append('photo', file)
    const returnedData = await this.$axios.$post('/api/photo/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
}

问题是:
我如何可以模拟上传照片在笑话测试我的代码?
我的笑话代码是这样的:

test('uploading photo test', () => {
wrapper = mount(UploadPhotoComponent, {
  stubs: {
    NuxtLink: true
  },
  mocks: {
    $auth: {
      loggedIn: true,
      $storage: {
        _state: {
          '_token.local': 'api bearer token'
        }
      }
    },
    $axios: {
      $post: jest.fn(() => {
        return Promise.resolve({
          status: 200,
          message: 'photo was uploaded successfully.',
          entire: []
        })
      })
    }
  }
  
  })
})

我不知道如何测试上传文件在笑话使用模拟。
有人能帮帮我吗?

bttbmeg0

bttbmeg01#

最后,我已经实现了如何做到这一点。首先生成一个图像blob和文件:

import fs from 'fs';
import path from 'path';

const dummyImgData = fs.readFileSync(
  path.join(__dirname, '../../libs/dummy-img-2.jpeg')
);

const fbParts = [
  new Blob([dummyImgData], {
    type: 'image/jpeg'
  }),
  'Same way as you do with blob',
  new Uint16Array([999999999999999])
];

const fbImg = new File(fbParts, 'sample.png', {
  lastModified: new Date(2020, 1, 1),
  type: 'image/jpeg'
});

将其赋值给$refs对象后:

wrapper.vm.$refs = {
  photo: {
    files: [
      fbImg
    ]
  }
}

相关问题