本文介绍了用Typescript开玩笑地嘲笑一个图书馆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想模拟一个GCP存储桶,但是Typescript由于打字而大喊大叫.

I want to mock a GCP bucket but Typescript is yelling because of typings.

这是我要测试的课程的摘录:

Here's an extract of a Class I want to test:

private storage = new Storage({
  projectId: 'PROJECT_NAME',
  keyFilename: env.gcpKeyFilename,
});

get bucket() {
  return this.storage.bucket('fundee-assets');
}

private async _downloadFromBucket(name) {
  const file = this.bucket.file(`${name}`);
  const destination = `${name}`.split('/').pop();
  await file.download({ destination, validation: false });
  return destination;
}

我不会开玩笑地嘲笑GCP存储桶的一部分.所以我尝试了:

I wan't to mock a part of the GCP bucket in jest. So I tried:

jest.spyOn(service, 'bucket', 'get').mockImplementationOnce(
  ()=>{
    return {
      file(name){
        return {
          download(dest, validation){
            return dest;
          }
        };
      }
    }
  }
)

打字稿之所以大喊是因为它不具备GCP存储桶类型的所有功能:

However typescript yells because it doesn't have all the prperties of a GCP Bucket typings:

Type '{ file(name: string): { download(dest: any, validation: any): any; }; }' is missing the following properties from type 'Bucket': name, storage, acl, iam, and 52 more.

关于如何绕过此方法的任何想法,或者我做的测试完全错误吗?

Any idea on how to bypass this or I am doing the test completely wrong?

推荐答案

以下是基于以下内容的解决方案:

Here is a solution based on:

"@google-cloud/storage": "^3.0.2",
"jest": "^23.6.0",
"ts-jest": "^23.10.4",
"typescript": "^3.0.3"

StorageService.ts:

import { Storage } from '@google-cloud/storage';

class StorageService {
  private storage = new Storage({
    projectId: 'PROJECT_NAME',
    keyFilename: ''
  });

  get bucket() {
    return this.storage.bucket('fundee-assets');
  }

  private async _downloadFromBucket(name) {
    const file = this.bucket.file(`${name}`);
    const destination = `${name}`.split('/').pop();
    await file.download({ destination, validation: false });
    return destination;
  }
}

export { StorageService };

单元测试:

import { StorageService } from './';

const mockedFile = {
  download: jest.fn()
};

const mockedBucket = {
  file: jest.fn(() => mockedFile)
};

const mockedStorage = {
  bucket: jest.fn(() => mockedBucket)
};

const storageService = new StorageService();

jest.mock('@google-cloud/storage', () => {
  return {
    Storage: jest.fn(() => mockedStorage)
  };
});

describe('StorageService', () => {
  describe('#_downloadFromBucket', () => {
    it('t1', async () => {
      const name = 'jest/ts';
      // tslint:disable-next-line: no-string-literal
      const actualValue = await storageService['_downloadFromBucket'](name);
      expect(mockedBucket.file).toBeCalledWith(name);
      expect(mockedFile.download).toBeCalledWith({ destination: 'ts', validation: false });
      expect(actualValue).toBe('ts');
    });
  });
});

单元测试结果:

 PASS  src/__tests__/cloud-storage/57724058/index.spec.ts
  StorageService
    #_downloadFromBucket
      ✓ t1 (9ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.594s, estimated 4s

这篇关于用Typescript开玩笑地嘲笑一个图书馆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 13:20