简体   繁体   English

如何在 deno 中模拟我的 mongodb 数据库/客户端?

[英]How can I mock in deno my mongodb database/client?

I was trying to write some unit tests and mock some functions that make network calls and more.我试图编写一些单元测试并模拟一些进行网络调用的函数等等。 I see that Deno's testing module only provides asserts to work with.我看到 Deno 的测试模块只提供了可以使用的断言。 Is there a good library or something I can use for Deno to make mocks for tests?有没有一个好的库或者我可以用来为 Deno 制作模拟测试的东西?

Best regards Thnaks you for your help!最好的问候 感谢您的帮助!

There's no mocking functionality in the Deno Standard Library ( std ) but you can find a few libraries/modules/frameworks that provide mocking on deno.land/x . Deno 标准库 ( std ) 中没有 mocking 功能,但您可以在 deno.land/x 上找到一些提供deno.land/x的库/模块/框架。 Rhum , for example, provides mocks.例如, Rhum提供模拟。 Here's an example from their docs:这是他们文档中的一个示例:

class ToBeMocked { ... }

const mock = Rhum
  .mock(ToBeMocked)
  .withConstructorArgs("someArg") // if the class to be mocked has a constructor and it requires args
  .create();

Keep in mind that most Deno modules are still being actively developed so they may not have every piece of functionality just yet.请记住,大多数 Deno 模块仍在积极开发中,因此它们可能还没有具备所有功能。 I don't know if any of Node's testing frameworks work on Deno, but if so you could use one of those (Jest/Jasmine/Mocha etc.)我不知道 Node 的任何测试框架是否适用于 Deno,但如果可以,您可以使用其中之一(Jest/Jasmine/Mocha 等)

I have not personally used Deno's testing suite but mocking follows the same patterns throughout most testing frameworks.我没有亲自使用过 Deno 的测试套件,但 mocking 在大多数测试框架中都遵循相同的模式。 Generally you would define a mock object or function and you explicitly define the behavior to your liking.通常,您会定义一个模拟 object 或 function 并根据自己的喜好明确定义行为。

In terms of database calls, you would most likely mock the module or implementation making the call and return your expect mocked result.在数据库调用方面,您很可能会模拟进行调用的模块或实现并返回您期望的模拟结果。

Jest is a great testing framework that provides this ability. Jest 是一个很好的测试框架,可以提供这种能力。

Here is an example of mocking an Axios call ( https://jestjs.io/docs/mock-functions ).这是 mocking 和 Axios 调用的示例( https://jestjs.io/docs/mock-functions )。 You can replace the axios example for your mongodb scenario.您可以将 axios 示例替换为 mongodb 方案。

// users.js
import axios from 'axios';

class Users {
  static all() {
    return axios.get('/users.json').then(resp => resp.data);
  }
}

export default Users;
// users.test.js
import axios from 'axios';
import Users from './users';

jest.mock('axios');

test('should fetch users', () => {
  const users = [{name: 'Bob'}];
  const resp = {data: users};
  axios.get.mockResolvedValue(resp);

  // or you could use the following depending on your use case:
  // axios.get.mockImplementation(() => Promise.resolve(resp))

  return Users.all().then(data => expect(data).toEqual(users));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM