为 Discourse 中的 Ember 代码编写验收测试

自动化测试是保护代码免受未来回归影响的绝佳方式。许多人都熟悉如何在我们的 Rails 代码库中使用 rspec 来完成这项工作,但对于 Javascript 端,有些人可能觉得它有些神秘。

幸运的是,如今为 Ember 代码添加基本测试已经相当简单了!

有关组件测试,请参阅 组件测试。

验收测试

验收测试 通常更容易编写,而且可能比组件测试更强大,因为它们以用户浏览时同样的方式测试你的应用程序。我通常先编写验收测试,如果我要构建一个复杂的组件,我也会为它添加测试。

下面是我们如何编写一个验收测试,该测试将访问我们的 /admin/snack 路由并确认 snack 已渲染:

test/javascripts/acceptance/snack-test.js

import { acceptance } from "helpers/qunit-helpers";
acceptance("Snack");

test("Visit Page", function (assert) {
  visit("/admin/snack");
  andThen(() => {
    assert.ok(exists(".fancy-snack-title"), "the snack title is present");
  });
});

在这种情况下,test() 读起来几乎就像英语一样!第一个命令表示访问 URL /admin/snack。之后,有一个 andThen() 方法。此方法对于确保所有后台工作在测试继续之前完成是必要的。由于 Javascript 和 Ember 代码是异步的,我们需要确保 Ember 在执行我们的断言之前完成了它需要做的一切。最后,它测试 .fancy-snack-title 元素是否存在。

然而,如果你通过访问 /qunit?module=Acceptance%3A%20Snack 运行此测试,你会发现测试将由于 AJAX 错误而失败。

如果你还记得,我们的代码包含 Rails 端和 Javascript 端,后者执行 AJAX 请求以获取其数据。验收测试运行了 Javascript 端,但它不知道如何从 Rails 获取数据。

为了解决这个问题,我们需要使用优秀的 pretender 库添加一个伪造响应。打开 test/javascripts/helpers/create-pretender.js 文件,并查找如下所示的行:

this.get("/admin/plugins", () => response({ plugins: [] }));

在它正下方,添加一行代码,为验收测试返回一个伪造的 snack 对象:

this.get("/admin/snack.json", () => {
  return response({ name: "snack name", description: "snack description" });
});

你可以将上面的代码读作“对于任何对 /admin/snack.json 的请求,使用以下 response 进行响应。”

如果你刷新 URL /qunit?module=Acceptance%3A%20Snack,你的验收测试应该通过 pretender 获取数据,并且测试应该通过。

接下来做什么

你可以尝试构建一个小功能,并添加测试以确保其正常工作。你甚至可以尝试使用 TDD(测试驱动开发),在编写任何前端代码之前先创建测试。根据你正在处理的工作内容和个人偏好,你可能会发现这是一种更愉快的做事方式。祝你好运,编码愉快 :slight_smile:


此文档受版本控制 - 请在 github 上建议修改。

15 个赞

My prior experience in writing qunit tests was based on the other howto

i.e. “acceptance” was simply

acceptance("Purple Tentacle", { loggedIn: true });

I have seen in other plugins where the test code contained “fake” JSON to test against. I wasn’t sure if that would be as good as testing against “real” data, so I wanted to avoid doing it that way.

The six tests passed, but I got a couple of rather angry looking “unhandled request” errors.

After finding an example of some “setup” code, I tried it and it solved the errors.

It works, but I’m not really sure why, nor why it’s needed for some but not for the majority of plugins I’ve seen that have qunit tests.

3 个赞

For a long time we weren’t great with testing plugins, so not many people followed our example and added tests.

You are right to add a response using pretender to handle AJAX calls.

4 个赞

请注意,/qunit 路径已过时。现在是 /tests。我花了一段时间才弄明白 :slight_smile:

1 个赞