【问题标题】:Any example related to function testing and edge cases in javascript任何与 javascript 中的功能测试和边缘案例相关的示例
【发布时间】:2022-01-12 09:32:18
【问题描述】:

任何人都可以分享任何与 javascript 中的边缘案例测试相关的示例,以及任何与使用 jest 在 javascript 中进行功能测试相关的示例。

const activityFunction: AzureFunction = async function (context: Context): Promise<string> {
    try {
        let mappingArr = [] as any;
        mapCategoryNameToNameOfNetwork(mappingArr, context);
        return
    } catch (err) {
        context.log.error("Error while mapping category name to name of networks", err)
        throw err;
    }
};



I want to test this function as this is giving blank response. I am not able to test it like i was testing for normal functions. Do anyone have any solution that how i should move ahead with this?



提前感谢您的帮助。

【问题讨论】:

标签: javascript node.js jestjs azure-functions


【解决方案1】:
  1. 在 VS Code 中创建一个 Azure JavaScript 函数并在本地进行测试。

在这里,为 HTTP Trigger1 创建了一个文件夹。

  1. 在 VS Code 项目的根目录下创建另一个名为 testing 的文件夹,并在终端中以相同的顺序运行这些命令:
npm init -y
npm i jest

它将所需的包添加到项目中,以便用 jest 测试功能。

  1. 更新package.json以替换现有的测试命令:
    "scripts": {
        "test": "jest"
    }

看起来像:

  1. 在测试文件夹中,通过将其命名为 defaultContext.js 创建一个文件并添加以下代码:
    module.exports = {
        log: jest.fn()
    };

它在默认上下文中模拟日志功能。

  1. 在 Azure Function 文件夹(即 HTTP Trigger1 文件夹)中,通过添加以下测试代码来添加新文件 index.test.js:
    const httpFunction = require('./index');
    const context = require('../testing/defaultContext')
    
    test('Http trigger should return known text', async () => {
    
        const request = {
            query: { name: 'Bill' }
        };
    
        await httpFunction(context, request);
    
        expect(context.log.mock.calls.length).toBe(1);
        expect(context.res.body).toEqual('Hello Bill');
    });

这些是使用 Jest 运行 JavaScript Azure Function 的步骤和代码格式。

  1. 要运行测试,请在 VS Code 终端中使用此代码:npm test

如果测试失败,显示如下:

这里测试失败了,因为在测试脚本中,结果字符串应该是Hello {name},而在Azure Function Http Trigger的样板代码中,结果字符串是Hello, {name}. This function executed successfully.

所以两者都不匹配,测试失败。 修改 HTTP 触发函数,输出与测试脚本结果相同的结果字符串,即Hello {name}

测试通过,因为函数的输出是Hello Bill,这与测试脚本的预期输出相同。

以下是使用 Jest 的 Azure JavaScript 函数测试和边缘案例测试的参考:

  1. Microsoft Documentation of Azure JavaScript Functions Testing & Debugging
  2. Edge Cases Testing Code in the Functions
  3. Testing JavaScript with Jest

【讨论】:

  • 你回答了我一半的问题。但是在回复中,我得到了空白的回复。所以我想知道如何测试返回空白响应的函数。
  • @AnshulSharma,请检查您执行的每个步骤,因为如果响应格式从测试代码到主代码不匹配,则不会记录响应,正如我在答案中提到的那样。
  • @AnshulSharma,该问题有任何更新吗?
  • 正如您所提到的,如果响应格式从测试代码到主代码不匹配,则没有响应记录,正如我在答案中提到的,那么我们如何在这种情况下进行测试。
  • @AnshulSharma,我已经向您展示了格式不匹配的失败案例以及答案中的成功输出。请检查答案!
猜你喜欢
  • 2023-01-18
  • 1970-01-01
  • 2010-10-28
  • 2011-08-05
  • 2019-07-29
  • 2012-10-19
  • 1970-01-01
  • 1970-01-01
  • 2016-03-30
相关资源
最近更新 更多