gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:02:38 25 4
gpt4 key购买 nike

我想用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com