简体   繁体   English

如何接近以下 TypeScript 代码进行测试?

[英]How to approach the following TypeScript code for testing?

I have been asked to test the following code, but have no idea about it.我被要求测试以下代码,但对此一无所知。

import AWS from 'aws-sdk';
import db from './db';

async function uploadUserInfo(userID: number) {
const user = db.findByPk(userID);
    if(!user) throw new Error('User not Found')
const S3 = new AWS.S3();
await S3.putObject({
    Bucket: 'users',
    Key:userID,
    Body: JSON.stringify(user.get())
})
    
}

As far as I understand the code, it is an asynchronous function to upload user information, validate it, and uses a new instance of a AWS Class to put the userId into the database.据我了解代码,它是一个异步的 function 上传用户信息,验证它,并使用 AWS Class 的新实例将 userId 放入数据库。

You might need to test it by inputing different values of UserID .您可能需要通过输入不同的UserID值来测试它。 Since I assume no other part of code has been given, you need to test it with varied input values only, and play around with the Error handling由于我假设没有给出代码的其他部分,因此您只需要使用不同的输入值对其进行测试,并尝试使用错误处理

As written, the function won't run as it has what appears to be an undeclared variable ( order ).如所写, function 不会运行,因为它似乎有一个未声明的变量 ( order )。 So you can probably test that and return it to the dev as 'broken'.因此,您可以对其进行测试并将其作为“损坏”返回给开发人员。

It's testable assuming your test environment knows the database content, and that the AWS credentials are correct (and presumably not a live/production instance).它是可测试的,假设您的测试环境知道数据库内容,并且 AWS 凭证是正确的(并且可能不是实时/生产实例)。 If this is true, then you can supply known userID values and check that the AWS bucket receives the data.如果这是真的,那么您可以提供已知的 userID 值并检查 AWS 存储桶是否接收到数据。

The function is not well implemented in that its dependencies (db and AWS) are not injectable, and therefore they cannot easily be substituted with mock implementations for testing purposes. function 没有很好地实现,因为它的依赖项(db 和 AWS)是不可注入的,因此它们不能轻易地被模拟实现替换以用于测试目的。

Some testing tools might allow you to intercept the module loading so that you can provide a mock db and AWS implementation, and that would allow you to check that the relevant calls are made with the correct data, based on the userID parameter.一些测试工具可能允许您拦截模块加载,以便您可以提供模拟数据库和 AWS 实现,这将允许您根据 userID 参数检查是否使用正确的数据进行了相关调用。

If you have the ability to modify the function so that it is more testible, then if you add the db and AWS instance as parameters, then you can supply mocks, and use those to validate the internal implementation.如果您有能力修改 function 以使其更易于测试,那么如果您添加数据库和 AWS 实例作为参数,那么您可以提供模拟,并使用它们来验证内部实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM