имитировать загрузку файла с помощью test jest, сервер apollo в nodejs - PullRequest
0 голосов
/ 29 мая 2020
• 1000 *
//IngredientClient.js
const gql = require('graphql-tag');

const Ingredient_create = gql`
 mutation (
  $name: String! 
  $file: Upload!
 ){
 ingredientCreate (
  name: $name
  file: $file   
  ){
    id
    name
 } 
} 
`;
module.exports = { Ingredient_create }

// IngredientResolver. js

 const fs = require('fs');

 storeFile(stream, path) {

   return new Promise((resolve, reject) =>
        stream
            .on('error', error => {
                if (stream.truncated)
                    // delete the truncated file
                    fs.unlinkSync(path);
                reject(error);
            })
            .pipe(fs.createWriteStream(path))
            .on('error', error => reject(error))
            .on('finish', () => resolve({ path }))
    );

 }

 const resolvers = {

Mutation: {
    async  ingredientCreate(_, args) {

    const { createReadStream, filename, mimetype, encoding } = data_file;
    const path = `${upload_path}/${filename}`;

    const file = await File.create({
        filename,
        mimetype,
        encoding,
        path
    })

    const stream = createReadStream()
    await storeFile(stream, path)

    },

 }

}

module.exports = resolvers;

// ingrendientMutation.test. js

const server = require('../../../src/app')
const { Ingredient_create } = require('./IngredientClient')
const { createTestClient } = require('apollo-server-testing');
const { mutate } = createTestClient(server);
const faker = require('faker')
const fs = require('fs')    

describe('Module ingredient all mutations', () => {


it('should insert a ingrendient with upload of file', async () => {

    var formData = fs.createReadStream(__dirname + '/tomato.png', { encoding: 'utf8' })

    const name = faker.name.findName();

    const result = await mutate({
        mutation: Ingredient_create, variables: {
            name: name,
            file: formData

        },
        context: {
            useMultipart: true
        }

    });

    expect(result.data.ingredientCreate).toBe('test');

}, 300)

})

сущность ссылки: https://gist.github.com/tiagobrunoBFR/3485bb5cd79d27537b506c00f87a10ec

...