当前位置: 首页 > 工具软件 > AVA > 使用案例 >

942.ava.com_如何使用Ava.js测试Node.js应用程序

马梓
2023-12-01

942.ava.com

by Nitish Phanse

由Nitish Phanse

如何使用Ava.js测试Node.js应用程序 (How you can test your Node.js applications with Ava.js)

Why would you want to write test cases for your applications, anyway? Well, it’s a question a number of developers try to dodge, purely because it takes effort and time, and because manual testing is so much more satisfying. Click… click… fill out a form…Click… Presto. My app works, my APIs are good, all is hunky dory.

无论如何,为什么要为应用程序编写测试用例? 嗯,这是许多开发人员试图躲避的问题,这纯粹是因为这需要花费时间和精力,并且因为手动测试更加令人满意。 单击...单击...填写表格...单击... Presto。 我的应用程序正常运行,我的API很好,一切都是笨拙的。

Fast forward to almost 30 pull requests a day being merged into your master branch. Now how do you feel about testing 30 features manually or refactoring a block of code and unknowingly breaking someone else’s code?

每天将近30个请求合并到您的master分支中。 现在,您对手动测试30个功能或重构代码块并在不知不觉中破坏他人代码的感觉如何?

At this point you’d normally say, “I wish I’d written a few test cases to start with.” So take some inspiration from Facebook: they shared a pretty cool article here, explaining how the team developed React 16 with test driven development.

此时,您通常会说:“我希望我先写一些测试用例。” 因此,请从Facebook获得一些启发:他们在这里分享了一篇很酷的文章,解释了团队如何通过测试驱动开发来开发React 16。

Node applications by themselves are pretty easy to build. There’s a lot of community support involved, and you’ll usually get what you need by asking around. Node apps can be a great proxy server to a number of API servers, thereby making their endpoint testing more crucial.

节点应用程序本身很容易构建。 涉及到很多社区支持,通常您可以通过询问来获得所需的东西。 节点应用程序可以成为许多API服务器的出色代理服务器,从而使它们的端点测试更加关键。

In this article I’ve covered how to setup and write basic unit test cases with coverage reports for Node.js applications. So let’s jump in.

在本文中,我介绍了如何使用Node.js应用程序的覆盖率报告设置和编写基本的单元测试用例 因此,让我们进入。

你好阿娃 (Hello Ava)

Ava is a JavaScript test runner. It utilizes the async I/O nature of Node and runs concurrent tests, thereby vastly decreasing your test times.

Ava是JavaScript测试人员。 它利用Node的异步I / O特性并运行并发测试,从而大大减少了测试时间。

让我们开始吧 (Let’s get started)

In your working directory, create a package.json file and add the following packages:

在您的工作目录中,创建一个package.json文件并添加以下软件包:

yarn add ava babel-register

Create a tests folder. It’s helpful to keep your tests in one place. You can keep test modules/controllers there, too.

创建一个测试文件夹。 将您的测试放在一个地方很有帮助。 您也可以将测试模块/控制器保留在那里。

Your updated package.json should now look like this:

更新后的package.json现在应如下所示:

{  "name": "ava-test",  "version": "1.0.0",  "description": "",  "main": "index.js",  "scripts": {    "start" : "node server.js",    "test": "node_modules/.bin/ava tests/**/*.test.js --verbose",    "test:watch": "node_modules/.bin/ava --verbose --watch"  },  "dependencies": {    "ava": "^0.23.0",    "babel-register": "^6.26.0"  },  "ava": {    "require": [      "babel-register"    ]  }}

The babel-register transpiles ES6 code at runtime in case some machines are running on an old Node version which doesn’t support ES6. The verbose flag will give us some neat output depending on whether our tests fail or pass. This flag is pretty useful while debugging your tests, but if you write hundreds of test cases, you may want to turn it off.

如果某些机器在不支持ES6的旧Node版本上运行,则babel-register会在运行时转换ES6代码。 verbose标志将根据测试是否通过来给我们一些整洁的输出。 该标志在调试测试时非常有用,但是如果编写数百个测试用例,则可能需要将其关闭。

In your tests/index.test.js, you can add your first test case:

在您的tests/index.test.js ,您可以添加第一个测试用例:

The handy thing about Ava is that it allows you to run async tests, via async await functions. The syntax is also fairly straightforward. The plan method allows us to explicitly mention the number of assertions we’d like to have per test.

关于Ava的方便之处在于,它允许您通过异步等待功能运行异步测试。 语法也很简单。 通过plan方法,我们可以明确提及每个测试要拥有的断言数量。

Running yarn test from you console gives you the following output:

从控制台运行yarn test将为您提供以下输出:

In case one of our tests fails, we’d get:

万一我们的测试失败了,我们会得到:

That’s the beauty of verbose mode. It gives you the a clean error stack and none of the stack trace junk. In case you run into a runtime error, you’ll see some nice syntax highlighting, too.

这就是verbose模式的美。 它为您提供了一个干净的错误堆栈,并且没有堆栈跟踪垃圾。 万一遇到运行时错误,您还将看到一些不错的语法突出显示。

You can really exploit the Ava API and use its powerful assertion tool to write flexible test cases.

您可以真正利用Ava API并使用其强大的断言工具来编写灵活的测试用例。

设置节点服务器 (Setting up your Node server)

Until now, we’ve only talked about a basic setup for writing tests — and let’s be frank, it’s pretty straight forward. So in this section, I’ll explain how a simple Node server can be spun off and its endpoints tested with Ava.

到目前为止,我们仅讨论了编写测试的基本设置-坦率地说,这非常简单。 因此,在本节中,我将说明如何剥离简单的Node服务器以及如何使用Ava测试其端点。

yarn add express body-parser

In your working directory, create an app.js and add the following snippet:

在您的工作目录中,创建一个app.js并添加以下代码段:

The reason I’ve exported the app module is so that it can be used with the mock API server that Ava will need to run your tests.

我导出app模块的原因是,它可以与Ava运行测试所需的模拟API服务器一起使用。

Make a new file server.js and import the app module to start the server.

创建一个新文件server.js并导入app模块以启动服务器。

Running npm start should start your server, and navigating to the http://localhost/status end point should give you a 200OK response.

运行npm start应该会启动您的服务器,导航到http:// localhost / status端点应该会给您200OK的响应。

Great, so our server is working.

太好了,因此我们的服务器正在运行。

A quick glance of the code shows that we’ve created 3 endpoints: a status endpoint, a greet endpoint, and a register endpoint. There is some validation on the register end point, which throws a 400(Bad request) in case post body params are missing. The above validation method is pretty naïve, but it serves our purpose of endpoint testing — so I’m going to stick with it.

快速浏览一下代码,就可以看到我们创建了3个端点:状态端点,问候端点和寄存器端点。 寄存器端点上有一些验证,如果缺少后正文参数,则会抛出400(错误请求)。 上面的验证方法还很幼稚,但是它可以达到我们进行端点测试的目的-因此我将坚持使用。

Pro tip : You can always assign error handling to a middleware and use next to invoke the error handler.

专家提示:您始终可以将错误处理分配给中间件,并使用next来调用错误处理程序。

Let’s write some more tests around the endpoint. I will use the supertest module. It’s very similar to superagent: it uses the same APIs, and has a similar syntax. So, win-win.

让我们围绕端点编写更多测试。 我将使用超级测试 模块。 它与superagent非常相似:它使用相同的API,并且具有相似的语法。 所以,双赢。

We have imported the previously exported app module and passed it into supertest. Supertest creates a proxy server, which will then hit all the endpoint URLs mentioned in the test. You can use the deepEqual method to test the entire object or the is method to manually test each field.

我们已经导入了先前导出的app模块,并将其传递给了supertest。 Supertest创建了一个代理服务器,该代理服务器随后将命中测试中提到的所有端点URL。 您可以使用deepEqual方法测试整个对象,也可以使用is方法手动测试每个字段。

Running the yarn test will yield the following:

运行纱线测试将产生以下结果:

Great. We’ve written four tests and they all pass as expected. But what about code coverage?

大。 我们已经编写了四个测试,并且都通过了预期的测试。 但是代码覆盖率呢?

你好纽约 (Hello nyc)

For creating those lovely coverage reports, we’ll use nyc which is Istanbul.js’ command line interface. It’s very easy to use and has a lot of configurable options. For the sake of simplicity, we’ll use a very simple configuration.

为了创建可爱的覆盖率报告,我们将使用nyc ,这是Istanbul.js的命令行界面。 它非常易于使用,并且具有许多可配置的选项。 为了简单起见,我们将使用非常简单的配置。

yarn add nyc --save

The nyc command wraps nicely over your test command and will create a coverage folder (this should be in your gitignore) in your working directory.

nyc命令很好地包装了您的测试命令,并将在您的工作目录中创建一个coverage文件夹(应在gitignore中)。

Update your package.json as shown below:

如下所示更新您的package.json

{  "name": "ava-test",  "version": "1.0.0",  "description": "",  "main": "index.js",  "scripts": {    "test": "node_modules/.bin/ava tests/**/*.test.js --verbose",    "test:watch": "node_modules/.bin/ava --verbose --watch",    "cover": "node_modules/.bin/nyc yarn test",  },  ... other dependencies   "nyc": {    "reporter": [      "lcov",      "text",      "html"    ]  }}

The types of reporter you want can be configured in the nyc section of your package.json file.

您可以在package.json文件的nyc部分配置所需的报告程序类型。

Let’s run yarn cover:

让我们运行纱套:

Okay so we don’t have 100% coverage yet. Let’s fix that. First you’d want to go into the coverage folder of your working directory and see which part of your code hasn’t been covered.

好的,我们还没有100%的覆盖率。 让我们修复它。 首先,您想进入工作目录的coverage文件夹,查看未覆盖代码的哪一部分。

Clearly we missed a spot. Let’s add our final test case in the tests/index.tests.js file, which will cover the entire app.js file.

显然我们错过了一个地方。 让我们将最终测试用例添加到tests/index.tests.js文件中,该文件将覆盖整个app.js文件。

test('Create a new user', async t => {  let username = 'some-hase'  const password = 'some-hase'  const response = await request(app)    .post('/register')    .send({username, password});
t.is(response.status, 200);    t.is(response.body.message, `new user created`);});

And now….

现在…。

Presto.

Presto。

Pro tip: If you want to add a threshold for test cases you can add a script in your package.json file.

专家提示: 如果要为测试用例添加阈值,则可以在package.json文件中添加脚本。

"check-coverage": "node_modules/.bin/nyc check-coverage --lines 100 --functions 100 --branches 100 --statements 100"

This command can be run as part of your travis / gitlab pipeline build systems.

该命令可以作为travis / gitlab管道构建系统的一部分运行。

结论 (Conclusion)

We’ve covered a basic setup with Ava for unit test cases of your Node APIs. The documentation is really extensive and can be referred to in case of doubt.

我们已经介绍了Ava的基本设置,用于您的Node API的单元测试用例。 该文档确实非常详尽,如有疑问,可以参考。

PS: Hope you like the article, correct me if I am wrong anywhere. Always welcome a discussion.

PS:希望您喜欢这篇文章,如果我在任何地方错了,请纠正我。 随时欢迎讨论。

翻译自: https://www.freecodecamp.org/news/testing-your-nodejs-applications-with-ava-js-99e806a226a7/

942.ava.com

 类似资料: