如何用玩笑来模拟azure-storage表服务功能?

时间:2020-06-03 18:05:01

标签: javascript jestjs azure-storage

我具有调用天蓝色表存储的功能:

const azure = require('azure-storage');
...
function getProductMetadata(sku, locale) {
    const retryPolicy = new azure.ExponentialRetryPolicyFilter(0, 200, 200, 600);
    const tableSvc = azure.createTableServiceWithSas(HOST, `?${AUTH}`).withFilter(retryPolicy);
    const payloadFormat = azure.TableUtilities.PayloadFormat.MINIMAL_METADATA;
    const partition = `${sku}-description`;

    return new Promise<PDAPIProduct.Tabledata>((resolve) => {
        tableSvc.retrieveEntity('ProductMetadata', partition, locale, { payloadFormat }, (error, result, response) => {
            if (get(response, 'statusCode') === 404) {
                resolve(null);
            } else {
                resolve(response.body);
            }
        });
    });
}

这个功能的测试:

const azure = require('azure-storage');
jest.mock('azure-storage');
const tableServiceMock = {
    retrieveEntity: jest.fn,
    withFilter: jest.fn,
}
azure.createTableServiceWithSas.mockImplementationOnce(() => tableServiceMock);

afterEach(jest.clearAllMocks);

describe('Product module', () => {
    describe('getProductMetadata', () => {
        test('getProductMetadata via azure storage SDK', async () => {
            const retValue = await pdApiProductService.getProductMetadata('213123123', 'en-CA');

            ///expect( something) 
        });
    });
});

但是当我跑步时,它会出错:

 TypeError: tableSvc.retrieveEntity is not a function

我在做什么错了?

顺便说一句,我的测试基于这篇文章: https://medium.com/@lakshaykaushik2506/azure-functions-unit-testing-mocking-azure-storage-npm-module-with-jest-34316fac6a69

1 个答案:

答案 0 :(得分:0)

我尝试了下面的代码,它可以工作。 document是表列,我将JSON文档存储为字符串。

const result = { document: { _: '{ "status": "OK" }' } };

const retrieveFn = (table, partitionKey, rowKey, callback) => {
  callback(null, result, { success: true });
}

const tableServiceMock = {
  retrieveEntity: retrieveFn
}
azure.createTableService.mockImplementationOnce(() => tableServiceMock);