用Typescript嘲笑一个图书馆

时间:2019-08-30 09:28:23

标签: typescript unit-testing google-cloud-platform jestjs

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

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

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存储桶的一部分。所以我尝试了:

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

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

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.

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

1 个答案:

答案 0 :(得分:2)

这是基于以下解决方案:

"@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