file-upload - 如何在 Jest 中模拟文件上传或文件对象?

标签 file-upload graphql jestjs apollo-server

我想用 jest 模拟文件上传来测试我的阿波罗服务器,我使用 graphql 来定义和传递数据。但是我发现在 Jest 中模拟文件对象非常困难。我用谷歌搜索并花了很多时间,但仍然找不到答案。

正如有人建议的那样,我使用这种方法。 https://gist.github.com/josephhanson/372b44f93472f9c5a2d025d40e7bb4cc ,

但是当我看到后端的返回时,它告诉我 createreadstream 不是一个函数。

这是我定义的graphql。

type Mutation{
changeFlowStatus(flowLog: FlowLogInput!, files: [Upload!], newStatus: Status): FlowLog
}
resolvers{
Upload: GraphQLUpload,
Mutation: {
  changeFlowStatus:
}

这是 Jest 部分。
    //changeFlowStatus
    var size = 1024 * 1024 * 2;
    var mock = new MockFile();
    const file = mock.create("pic.jpg", size, "image/jpeg");
    const changeFlowStatus = await toPromise(
      graphql({
        query: CHANGE_FLOW_STATUS,
        variables: {
          flowLog: { reflowId: reflowId, timestamp: '1562716800', comment: 'flowLog_comment', title: 'flowLog_title' },
          files: [file],
          newStatus: 'SP_RECEIVED',
        },
        context: {
          useMultipart: true,
        },
      }),
    );

file是我用上面提到的类创建的对象。

我的期望很简单,用 Jest 模拟文件上传过程或文件对象。谢谢。

最佳答案

我想你使用 apollographql , graphql-uploadjest.js ,这里是文件上传的集成测试:

it('should upload file correctly', async () => {
    const body = new FormData();
    body.append(
      'operations',
      JSON.stringify({
        query: `
          mutation ($file: Upload!) {
            singleUpload(file: $file) {
              code
              message
            }
          }
        `,
        variables: {
          file: null,
        },
      }),
    );

    const filename = '15625760447371547012340909WX20190108-124331.png';
    body.append('map', JSON.stringify({ 1: ['variables.file'] }));
    body.append('1', fs.createReadStream(path.resolve(__dirname, `./files/${filename}`)));
    const json = await fetch('http://localhost:4000', { method: 'POST', body }).then((response) => response.json());
    // logger.debug('upload testing#1', { arguments: { json } });
    expect(json).toEqual(
      expect.objectContaining({
        data: {
          singleUpload: {
            code: expect.any(Number),
            message: expect.any(String),
          },
        },
      }),
    );
  });

Github example repo

关于file-upload - 如何在 Jest 中模拟文件上传或文件对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57506231/

相关文章:

javascript - 单元测试导出的模块功能

javascript - super 测试未找到错误测试快速端点

PHP 警告 : move_uploaded_file() unable to move

java - GraphQL错误: Expected a user-defined GraphQL scalar type with name 'FileUpload' but found none

java - 如何使用HtmlUnit java上传<input multiple>中的多个文件

sql - Hasura GraphQL 查询 : where clause with value from related entity

amazon-web-services - AWS GraphQL Appsync - 无法承担角色

reactjs - enzyme shallowWrapper.setState 不适用于redux 连接组件

ios - 在 Swift 中使用多部分表单数据 iOS 上传图像

javascript - SAPUI5 文件 uploader : Cannot find and append file to FormData()