如何在玩笑中模拟文件上传或文件对象?

Li *_*ang 5 file-upload jestjs graphql apollo-server

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

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

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

这是我定义的graphql。

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

这是开玩笑的部分。

    //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,
        },
      }),
    );

Run Code Online (Sandbox Code Playgroud)

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

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

sli*_*wp2 3

我想你使用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),
          },
        },
      }),
    );
  });
Run Code Online (Sandbox Code Playgroud)

请参阅Github 示例存储库