【问题标题】:How do I mock azure-storage table service functionality with jest?如何用 jest 模拟 azure-storage 表服务功能?
【发布时间】:2020-09-22 13:19:36
【问题描述】:

我有这个调用azure table 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

【问题讨论】:

  • 当我在函数中 console.log tableSvc 时,在测试运行下我得到这个: tableSvc: function mockConstructor() { return fn.apply(this, arguments);所以它似乎没有得到完整的模拟实现:( .. 不知道如何解决这个问题。

标签: javascript jestjs azure-storage


【解决方案1】:

我尝试了下面的代码,它可以工作。 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);

【讨论】:

  • 我的问题是我在调用 createTableServiceWithSas 结束时使用了 withFilter() 并且这与测试混淆了。 Jest 不知道它是什么,即使我将它包含在模拟中。
猜你喜欢
  • 2021-11-19
  • 2019-09-18
  • 2023-01-30
  • 2022-06-28
  • 2021-11-01
  • 2022-10-25
  • 2019-08-28
  • 2019-07-16
  • 2020-08-22
相关资源
最近更新 更多