Jest.js 使用React Js测试时出错- TypeError:source.on不是函数

fcwjkofz  于 11个月前  发布在  Jest
关注(0)|答案(1)|浏览(141)

我有一个带有multipart/form-data的post请求。一切正常,但测试不正常。当我运行测试时,我得到:TypeError:source.on is not a function

这是我的请求:

images.forEach(async (image) => {
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${user}`
        }
      }

      const formData = new FormData();
      formData.append('workId', JSON.stringify(workId));
      formData.append('image', image.image, image.image.name);

      const data = {
        work_id: formData.get('workId'),
        url: formData.get('image'),
      }

      await api.post(`${baseUrl}/work/api/images/create/`, data, config)
      .then((r) => {
        console.log(`created successfully with status code ${r.status}`);
      })
      .catch((e) => {
        console.error(`this is the error: ${e.response.status}`);
      })
    })

字符串

这是我的考验

it('should returns success on create images', async () => {
    // mock the response
    server.use(
      http.post(`${baseUrl}/work/api/images/create/`, () => {
        return new HttpResponse(null, { status: 201 })
      }),
    )

    const user = userEvent.setup();
    
    handerImagesWorkManager(1, 'user');

    // mock the images
    const images = [
      new File(['text'], 'image-test.png', { type: 'image/png' }),
      new File(['text'], 'image-test2.png', { type: 'image/png' }),
    ];
    const inputUpload: HTMLInputElement = screen.getByTestId(/upload_images/i);
    await user.upload(inputUpload, images);

    // spy
    const spy = vi.spyOn(console, 'log');
    const submitButton = await screen.findByDisplayValue(/upload all images/i);

    await user.click(submitButton);

    expect(spy).toHaveBeenCalledWith("created successfully with status code 201");
  });


我知道问题出在发送文件/图像上,因为当从formData中删除图像时,测试工作。我已经尝试修改测试和请求代码,但是当一个工作时,另一个不工作。

kulphzqa

kulphzqa1#

我解决了这个问题。我没有正确地使用formData。我没有在请求中传递formData,而是分离了数据。

const formData = new FormData(); 
formData.append('work_id', JSON.stringify(workId)); 
formData.append('url', image.image, image.image.name);

await api.post(`${baseUrl}/work/api/images/create/`, formData, config)

字符串

相关问题