I want to mock file-upload with jest to test my apollo-server, I use graphql to define and pass data. But I find it is very difficult to mock file object in jest. I search with google and spend lots of time, but still can't find an answer.
As some guy suggest, I use this method. https://gist.github.com/josephhanson/372b44f93472f9c5a2d025d40e7bb4cc,
but when I see the return of the back-end, it tells me createreadstream is not a function.
This is the graphql I defined.
type Mutation{
changeFlowStatus(flowLog: FlowLogInput!, files: [Upload!], newStatus: Status): FlowLog
}
resolvers{
Upload: GraphQLUpload,
Mutation: {
changeFlowStatus:
}
This is the jest part.
//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
is the object I create with the class mentioned above.
My expectation is simple, mock a file-upload process or file object with jest. Thanks.
I suppose you use apollographql
, graphql-upload
and jest.js
, here is a integretion test for file upload:
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),
},
},
}),
);
});
See Github example repo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With