【问题标题】:Testing sharp with memfs error: [Error: Input file is missing]使用 memfs 错误测试尖锐:[错误:输入文件丢失]
【发布时间】:2021-11-01 14:06:03
【问题描述】:

我在测试实现sharpmemfs 的代码时遇到了问题。我有下载图像并将其裁剪到特定尺寸的代码。我使用sharp 来实现裁剪。在进行测试时,我使用jestmemfs。我的测试代码有两部分:

  1. 下载图像并保存到使用memfs 创建的模拟卷/文件系统。
  2. 使用sharp将下载的图像裁剪到特定尺寸。

第 1 部分运行良好,能够将图像下载到假卷并使用 jest 断言(存在于假卷中)。
但第 2 部分给了我错误:@987654333 @。

const sizeToCrop = {
            width: 378,
            height: 538,
            left: 422,
            top: 0,
        };

sharp(`./downloadedImage.jpg`)
            .extract(sizeToCrop)
            .toFile(`./CroppedImage.jpg`)
            .then(() => {
                console.log(`resolve!`);
            })
            .catch((err: Error) => {
                console.log(err);
                return Promise.reject();
            });

// Error message: [Error: Input file is missing]

但是当我用真实音量测试它时。效果很好。
任何人都知道如何解决这个问题? 谢谢。

【问题讨论】:

    标签: sharp


    【解决方案1】:

    经过hereherehere的一些启发

    这是因为sharp没有访问memfs'伪造的文件系统,它正在访问实际的fs'文件系统,而./donwloadedImage.jpg不存在。因此,为了使sharp 使用memfs,必须对其进行模拟。并且extracttoFile 函数也需要被模拟(用于链接函数调用):

    // Inside code.test.ts
    
    jest.mock('sharp', () => {
        const sharp = jest.requireActual('sharp');
        const { vol } = require('memfs');
        let inputFilePath: string;
        let sizeToCrop: any;
        let outputFilePath: string;
        const toFile = async (writePath: string): Promise<any> => {
            outputFilePath = writePath;
            try {
                return await starCropping();
            } catch (error) {
                console.log(`Error in mocked toFile()`, error);
            }
        };
        const extract = (dimensionSize: string): any => {
            sizeToCrop = dimensionSize;
            return { toFile };
        };
        const mockSharp = (readPath: string): any => {
            inputFilePath = readPath;
            return { extract };
        };
        async function starCropping(): Promise<void> {
            try {
                const inputFile = vol.readFileSync(inputFilePath);
                const imageBuffer = await sharp(inputFile).extract(sizeToCrop).toBuffer();
                vol.writeFileSync(outputFilePath, imageBuffer);
            } catch (error) {
                console.log(`Error in mocked sharp module`, error);
                return Promise.reject();
            }
        }
    
        return mockSharp;
    });
    

    【讨论】:

      猜你喜欢
      • 2020-06-22
      • 2021-07-10
      • 1970-01-01
      • 2020-11-30
      • 2023-01-24
      • 1970-01-01
      • 2015-04-03
      • 2021-12-14
      • 2014-09-29
      相关资源
      最近更新 更多