小编Efe*_*rav的帖子

Jest测试猫鼬模型实例化

我正在尝试测试使用express和mongoose构建的REST API,我正在使用jest和supertest进行http调用; 我也是用javascript测试相对较新的.

在测试创建URL时,我不想确保仅使用req.body对象调用实例化,但在阅读了很多关于模拟对象和存根之间的差异以及一些Jest之后,我不知道该怎么做我上次尝试的文档看起来像这样:

test('Should instantiate the model using req.body', done => {

  const postMock = jest.fn();

  const testPost = {
    name: 'Test post',
    content: 'Hello'
  };

  postMock.bind(Post); // <- Post is my model

  // I mock the save function so it doesn't use the db at all
  Post.prototype.save = jest.fn(cb => cb(null, testPost));

  // Supertest call
  request(app).post('/posts/')
  .send(testPost)
  .then(() => {
    expect(postMock.mock.calls[0][0]).toEqual(testPost);
    done();
  })
  .catch(err => {throw err});

});
Run Code Online (Sandbox Code Playgroud)

此外,我想知道如何手动失败的承诺拒绝测试,所以它不会抛出 Timeout - Async callback was not invoked within timeout …

javascript unit-testing mongoose express jestjs

2
推荐指数
1
解决办法
869
查看次数

标签 统计

express ×1

javascript ×1

jestjs ×1

mongoose ×1

unit-testing ×1