---
title: "谷哥的Javascript单元测试框架:Google JS Test"
author: "jeast"
date: "2012-04-17T21:36:59Z"
tags: []
categories: ["开源软件"]
slug: "javascript-google-js-test"
draft: false
lastmod: "2012-04-17T21:38:39Z"
id: 1488829
url: "https://lwe.iteye.com/blog/1488829"
---

[Google JS Test](http://code.google.com/p/google-js-test/)  是一个运行于V8 JavaScript引擎下的Javascript单元测试框架，其在Google内部负责对Chrome的快速JS执行速度进行测试，现在Google以开源工程开放大家使用。Google JS Test主要特性：

- 超快的启动速度和执行时间，不需要在浏览器里运行
- 清爽而具有可读性的输出内容
- 也有一个可选的基于浏览器的测试器，可在JS修改的时候刷新
- 其样式和语义跟[Google Test for C++](http://code.google.com/p/googletest/)类似
- 内置的Mocking框架只需要最简单的样板代码，其样式和语义基于[Google C++ Mocking Framework](http://code.google.com/p/googlemock/)
- 匹配系统允许表达式测试，并可直观的阅读输出的错误提示，内置了很多匹配器，用户也可自行添加

```
function UserInfoTest() {
  this.getInfoFromDb_ = createMockFunction();
  this.userInfo_ = new UserInfo(this.getInfoFromDb_);
}
registerTestSuite(UserInfoTest);

UserInfoTest.prototype.formatsUSPhoneNumber = function() {
  // Expect a call to the database function with the argument 0xdeadbeef. When
  // the call is received, return the supplied string.
  expectCall(this.getInfoFromDb_)(0xdeadbeef)
    .willOnce(returnWith('phone_number: "650 253 0000"'));

  // Make sure that our class returns correctly formatted output.
  expectEq('(650) 253-0000', this.userInfo_.getPhoneForId(0xdeadbeef));
};

UserInfoTest.prototype.returnsLastNameFirst = function() {
  expectCall(this.getInfoFromDb_)(0xdeadbeef)
    .willOnce(returnWith('given_name: "John" family_name: "Doe"'));

  // Make sure that our class puts the last name first.
  expectEq('Doe, John', this.userInfo_.getNameForId(0xdeadbeef));
};
```

   The test's output is clean and readable:

```
[ RUN      ] UserInfoTest.formatsUSPhoneNumber
[       OK ] UserInfoTest.formatsUSPhoneNumber
[ RUN      ] UserInfoTest.returnsLastNameFirst
user_info_test.js:32
Expected: 'Doe, John'
Actual:   'John Doe'

[  FAILED  ] UserInfoTest.returnsLastNameFirst
[ RUN      ] UserInfoTest.understandsChineseNames
[       OK ] UserInfoTest.understandsChineseNames
```