mock fs.readFile with typescript

huangapple go评论107阅读模式
英文:

mock fs.readFile with typescript

问题

I'm here to help with your code translation. Here's the translated code:

  1. 我试图模拟 fs.readFile
  2. ```javascript
  3. fs.readFile = jest.fn((_, callback) => callback(null, JSON.stringify('sample')));

我试图测试这个函数:

  1. export const readFileAsynchronously = async (pathToFile: string) => {
  2. const fullPath = join(__dirname, pathToFile);
  3. if (existsSync(fullPath)) {
  4. const fileContent = await readFile(fullPath);
  5. return fileContent.toString();
  6. }
  7. return null;
  8. };

我想测试这个函数而不读取实际文件,是否可能?
测试如下:

  1. test('如果文件存在应返回文件内容', async () => {
  2. jest.mock('fs');
  3. const existsSync = () => true;
  4. fs.existsSync = existsSync;
  5. fs.readFile = jest.fn((_, callback) => {
  6. return callback(null, JSON.stringify('sample'));
  7. });
  8. jest.mock('path');
  9. path.join = (path: string) => path;
  10. const pathToFile = './test.txt';
  11. const result = await readFileAsynchronously(pathToFile);
  12. expect(result).toEqual('sample');
  13. });

但我遇到了一个类型错误:
类型“Mock<any, [_: any, callback: any], any>”中未提供属性“promisify”,而在类型“typeof readFile”中是必需的。

我尝试了另一种变体:

  1. const mockedFs = fs as jest.Mocked<typeof fs>;
  2. const existsSync = () => true;
  3. fs.existsSync = existsSync;
  4. mockedFs.readFile.mockImplementationOnce(
  5. () =>
  6. new Promise(function (resolve) {
  7. return resolve('test');
  8. }),
  9. );

但我收到了一个错误:
TypeError: mockedFs.readFile.mockImplementationOnce 不是一个函数

我不知道如何解决它。请问能否帮助我?

  1. I hope this helps with your code translation. If you have any further questions or need assistance with specific issues in the code, please feel free to ask.
  2. <details>
  3. <summary>英文:</summary>
  4. I&#39;m trying to mock fs.readFile:

fs.readFile = jest.fn((_, callback) => callback(null, JSON.stringify('sample')));

  1. I&#39; m trying to test this function:

export const readFileAsynchronously = async (pathToFile: string) => {
const fullPath = join(__dirname, pathToFile);
if (existsSync(fullPath)) {
const fileContent = await readFile(fullPath);
return fileContent.toString();
}

return null;
};

  1. And I want to test this function without reading the real file, is it possible?
  2. The test is:

test('should return file content if file exists', async () => {
jest.mock('fs');
const existsSync = () => true;
fs.existsSync = existsSync;
fs.readFile = jest.fn((_, callback) => {
return callback(null, JSON.stringify('sample'));
});
jest.mock('path');
path.join = (path: string) => path;
const pathToFile = './test.txt';
const result = await readFileAsynchronously(pathToFile);
expect(result).toEqual('sample');
});

  1. But I&#39;ve got a type error
  2. Property `__promisify__` is not presented in type &quot;Mock&lt;any, [_: any, callback: any], any&gt;&quot; and is required in type &quot;typeof readFile&quot;.
  3. I&#39;ve tried one more variant:

const mockedFs = fs as jest.Mocked<typeof fs>;
const existsSync = () => true;
fs.existsSync = existsSync;
mockedFs.readFile.mockImplementationOnce(
() =>
new Promise(function (resolve) {
return resolve('test');
}),
);

  1. But I&#39;ve got an error:

TypeError: mockedFs.readFile.mockImplementationOnce is not a function

  1. I don&#39;t have any idea how to solve it. Please, could you help me?
  2. </details>
  3. # 答案1
  4. **得分**: 1
  5. 首先,`readFile` 不是一个 promise。你需要使用一个回调或者使用一个不同的函数 `readFileSync`
  6. 你的函数实现不正确,下面是修复后的版本:
  7. ```typescript
  8. import { join } from 'path';
  9. import { existsSync, readFile } from 'fs';
  10. export const readFileAsynchronously = async (pathToFile: string) => {
  11. const fullPath = join(__dirname, pathToFile);
  12. if (existsSync(fullPath)) {
  13. // 当回调被调用时,使其解析
  14. return new Promise((resolve, reject) => {
  15. readFile(fullPath, 'utf8', (error, fileContent) => {
  16. if (error) return reject(error);
  17. resolve(fileContent);
  18. });
  19. });
  20. }
  21. return Promise.reject(new Error('文件未找到'));
  22. };

以下是你的测试实现:

  1. jest.mock('fs', () => ({
  2. existsSync: jest.fn().mockResolvedValue(true),
  3. readFile: jest.fn().mockImplementation((path, options, callback) => {
  4. callback(null, '我的文件内容');
  5. }),
  6. }));
  7. test('应该在不实际读取文件的情况下解析', async () => {
  8. const result = await readFileAsynchronously('test.txt');
  9. expect(result).toBe('我的文件内容');
  10. });
英文:

First of all readFile is not a promise. You need to use a callback or use a different function readFileSync.

Your function is not implemented correctly, here is the fixed version

  1. import { join } from &#39;path&#39;;
  2. import { existsSync, readFile } from &#39;fs&#39;;
  3. export const readFileAsynchronously = async (pathToFile: string) =&gt; {
  4. const fullPath = join(__dirname, pathToFile);
  5. if (existsSync(fullPath)) {
  6. // Making it to resolve when callback is invoked
  7. return new Promise((resolve, reject) =&gt; {
  8. readFile(fullPath, &#39;utf8&#39;, (error, fileContent) =&gt; {
  9. if (error) return reject(error);
  10. resolve(fileContent);
  11. });
  12. });
  13. }
  14. return Promise.reject(new Error(&#39;File not found&#39;));
  15. };

And here is your test implementation

  1. jest.mock(&#39;fs&#39;, () =&gt; ({
  2. existsSync: jest.fn().mockResolvedValue(true),
  3. readFile: jest.fn().mockImplementation((path, options, callback) =&gt; {
  4. callback(null, &#39;my file content&#39;);
  5. }),
  6. }));
  7. test(&#39;should resolve without reading the actual file&#39;, async () =&gt; {
  8. const result = await readFileAsynchronously(&#39;test.txt&#39;);
  9. expect(result).toBe(&#39;my file content&#39;);
  10. });

huangapple
  • 本文由 发表于 2023年6月30日 00:39:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76583018.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定