模拟猫鼬返回未定义?

时间:2020-04-12 10:43:45

标签: javascript typescript unit-testing mongoose mocking

我正在编写一个单元测试,模拟我的猫鼬依赖关系并测试预期的交互作用。

但是,尽管清楚地模拟了.create()方法以返回IPostDocument的模拟实例(从Mongoose扩展了Document的模拟实例),但由于我的create方法,我一直收到“ TypeError:无法读取未定义的属性'save'”,一直返回未定义状态,就像忽略了我的设置一样。

被测方法:

  async create(
    title: string,
    author: string,
    technologies: string,
  ): Promise<IPostDocument> {
    const postToCreate = new Post(
      null,
      title,
      author,
      technologies,
      false,
      new Date(),
    );

    const post = await this.postModel.create(postToCreate);

    return await post.save();
  }

失败测试:

  it('should call create and save from Mongoose', async () => {
    const mockPostModel = TypeMoq.Mock.ofType<Model<IPostDocument>>();
    const mockPostDocument = TypeMoq.Mock.ofType<IPostDocument>();

    mockPostDocument
      .setup(x => x.save())
      .returns(async () => mockPostDocument.object);

    mockPostModel
      .setup(x => x.create(TypeMoq.It.isAnyObject))
      .returns(async () => mockPostDocument.object);

    const postsRepository = new PostsRepository(mockPostModel.object);
    await postsRepository.create('A title', 'An author', 'Tech');

    mockPostModel.verify(
      async x => await x.create(TypeMoq.It.isAny),
      TypeMoq.Times.atMostOnce(),
    );
  });

据我所知,当我运行create方法时,应该将post变量分配给返回的模拟文档,该文档上具有.save()方法,而不是“ undefined”。

任何人都可以发现问题所在吗?

谢谢

0 个答案:

没有答案
相关问题