[英]Mock exported class in Typescript Jest
嗨,我編寫了以下代碼來從 Azure Blob 存儲中獲取 Blob。
import { BlobServiceClient, ContainerClient, ServiceFindBlobsByTagsSegmentResponse } from '@azure/storage-blob';
import { GetBlobPageInput, GetBlobPageOutput, PutBlobItemsInput, GetBlobItem } from './interfaces/blob.service.interface';
export const getBlobsPage = async<T>(input: GetBlobPageInput) => {
const blobServiceClient = BlobServiceClient.fromConnectionString(input.blobConnectionString);
const iterator = blobServiceClient
.findBlobsByTags(input.condition)
.byPage({ maxPageSize: input.pageSize });
return getNextPage<T>({
iterator,
blobServiceClient,
blobContainer: input.blobContainer,
});
};
[...]
我正在嘗試為它編寫一個單元測試,但是當我嘗試從 @azure/storage-blob 模擬 BlobServiceClient 時遇到了麻煩。 我這樣編寫示例測試和模擬:
import { getBlobsPage } from './../../services/blob.service';
const fromConnectionStringMock = jest.fn();
jest.mock('@azure/storage-blob', () => ({
BlobServiceClient: jest.fn().mockImplementation(() => ({
fromConnectionString: fromConnectionStringMock,
})),
}));
describe('BLOB service tests', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should fetch first page and return function to get next', async () => {
const input = {
blobConnectionString: 'testConnectionString',
blobContainer: 'testContainer',
condition: "ATTRIBUTE = 'test'",
pageSize: 1,
};
const result = await getBlobsPage(input);
expect(fromConnectionStringMock).toHaveBeenCalledTimes(1);
});
});
但是當我嘗試運行測試時,我得到:
TypeError: storage_blob_1.BlobServiceClient.fromConnectionString is not a function
24 |
25 | export const getBlobsPage = async<T>(input: GetBlobPageInput) => {
> 26 | const blobServiceClient = BlobServiceClient.fromConnectionString(input.blobConnectionString);
| ^
27 |
28 | const iterator = blobServiceClient
29 | .findBlobsByTags(input.condition)
at nhsdIntegration/services/blob.service.ts:26:47
at nhsdIntegration/services/blob.service.ts:1854:40
at Object.<anonymous>.__awaiter (nhsdIntegration/services/blob.service.ts:1797:10)
at Object.getBlobsPage (nhsdIntegration/services/blob.service.ts:25:65)
at tests/services/blob.service.test.ts:27:26
at tests/services/blob.service.test.ts:8:71
關於如何正確實現 azure 模塊的模擬的任何提示?
我在 StackOverflow 上嘗試了幾個不同的答案,並查看了 web 上的文章(例如: https://dev.to/codedivoire/how-to-mock-an-imported-typescript-class-with-jest-2g7j )。 他們中的大多數都表明這是正確的解決方案,所以我想我在這里遺漏了一些小東西,但無法弄清楚。
導出的BlobServiceClient
應該是文字 object 但您現在是 mocking 為 function 這是問題所在。
因此,您可能需要簡單地模擬返回文字 object。 另一個問題是從模擬 scope 外部訪問 var fromConnectionStringMock
會導致另一個問題。
所以這可能是正確的模擬:
jest.mock('@azure/storage-blob', () => ({
...jest.requireActual('@azure/storage-blob'), // keep other props as they are
BlobServiceClient: {
fromConnectionString: jest.fn().mockReturnValue({
findBlobsByTags: jest.fn().mockReturnValue({
byPage: jest.fn(),
}),
}),
},
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.