如何使用 sinon 测试异步函数?

How to test asynchonous functions using sinon?

我有一个名为 PostController 的 class,我正在尝试测试以下创建函数:

class PostController {
  constructor(Post) {
    this.Post = Post;
  }

  async create(req, res) {
    try {
      this.validFieldRequireds(req);
      const post = new this.Post(req.body);
      post.user = req.user;
      ...some validations here
      await post.save();
      return res.status(201).send(message.success.default);
    } catch (err) {
      console.error(err.message);
      const msg = err.name === 'AppError' ? err.message : 
      message.error.default;
      return res.status(422).send(msg);
    }
 }

我的测试class是:

import sinon from 'sinon';
import PostController from '../../../src/controllers/posts';
import Post from '../../../src/models/post';

describe('Controller: Post', async () => {
  it.only('should call send with sucess message', () => {
    const request = {
      user: '56cb91bdc3464f14678934ca',
      body: {
        type: 'Venda',
        tradeFiatMinValue: '1',
        ... some more attributes here
      },
    };
    const response = {
      send: sinon.spy(),
      status: sinon.stub(),
    };

    response.status.withArgs(201).returns(response);
    sinon.stub(Post.prototype, 'save');
    const postController = new PostController(Post);

    return postController.create(request, response).then(() => {
      sinon.assert.calledWith(response.send);
    });
  });
});

但我收到以下错误:

Error: Timeout of 5000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (D:\projeto\mestrado\localbonnum-back-end\test\unit\controllers\post_spec.js)

为什么?

很有可能是因为误用了sinon.stub

sinon.stub(Post.prototype, 'save');

没有说明这个存根会做什么,所以原则上这个存根什么都不做(意思是 returns undefined)。 IDK,为什么你看不到其他类似的尝试在存根上等待。 尽管如此,您应该正确配置 'save' 存根 - 例如像这样:

const saveStub = sinon.stub(Post.prototype, 'save');
saveStub.resolves({foo: "bar"});