javascript 中与功能测试和边缘情况相关的任何示例

Any example related to function testing and edge cases in javascript

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

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?



在此先感谢您的帮助。

  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 函数文件夹(即 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 函数的步骤和代码格式。

  1. 为了运行测试,在VS代码终端中使用这个代码:npm test

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

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

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

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

以下是 Azure JavaScript 使用 Jest 进行功能测试和边缘案例测试的参考资料:

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