Let's implement a module that fetches user data from an API and returns the user name.

In the above implementation we expect the module to return a promise. We chain a call to then to receive the user name.

Now imagine an implementation of request.js that goes to the network and fetches some user data:

  1. // request.js
  2. const http = require('http');
  3. export default function request(url) {
  4. return new Promise(resolve => {
  5. // 这是一个HTTP请求的例子, 用来从API获取用户信息
  6. // This module is being mocked in __mocks__/request.js
  7. http.get({path: url}, response => {
  8. let data = '';
  9. response.on('data', _data => (data += _data));
  10. response.on('end', () => resolve(data));
  11. });
  12. });
  13. }

现在我们就来编写我们的异步函数的测试

  1. jest.mock('../request');
  2. //断言必须返回一个primose
  3. it('works with promises', () => {
  4. expect.assertions(1);
  5. return user.getUserName(4).then(data => expect(data).toEqual('Mark'));
  6. });

我们调用 jest.mock('../request ') 告诉jest 使用我们手动的创建的模拟数据。 it 断言的是将会返回一个Promise对象. You can chain as many Promises as you like and call expect at any time, as long as you return a Promise at the end.

There is a less verbose way using resolves to unwrap the value of a fulfilled promise together with any other matcher. If the promise is rejected, the assertion will fail.

  1. // 使用async/await
  2. it('works with async/await', async () => {
  3. expect.assertions(1);
  4. const data = await user.getUserName(4);
  5. expect(data).toEqual('Mark');
  6. });
  7. // async/await 也可以和 `.resolves` 一起使用.
  8. expect.assertions(1);
  9. });

To enable async/await in your project, install @babel/preset-env and enable the feature in your babel.config.js file.

可以使用 .catch 方法处理错误。 请确保添加 expect.assertions 来验证一定数量的断言被调用。 否则一个fulfilled态的Promise 不会让测试失败︰

The.rejects helper works like the .resolves helper. 如果 Promise 被拒绝,则测试将自动失败。

  1. // 用`.rejects`.来测试一个异步的错误
  2. it('tests error with rejects', () => {
  3. expect.assertions(1);
  4. return expect(user.getUserName(3)).rejects.toEqual({
  5. error: 'User with 3 not found.',
  6. });
  7. });
  8. // 或者与async/await 一起使用 `.rejects`.
  9. it('tests error with async/await and rejects', async () => {
  10. expect.assertions(1);
  11. await expect(user.getUserName(3)).rejects.toEqual({
  12. error: 'User with 3 not found.',
  13. });

If you'd like to test timers, like , take a look at the documentation.