简体   繁体   English

用 Jest 和 sequelize-mock 模拟 sequelize

[英]Mock sequelize with Jest and sequelize-mock

I'm building a new project and I'm trying to use TDD as my default methodology and trying to apply it with integration test.我正在构建一个新项目,我正在尝试使用 TDD 作为我的默认方法,并尝试将它与集成测试一起应用。

The thing is easy I want to retrieve all the users from my DB.事情很简单,我想从我的数据库中检索所有用户。

//controller.js
const UserService = require('../services/user');

module.exports = {
  // corresponds to /users
  getAllUsers: async (req, res, next) => {
    const users = await UserService.fetchAllUsers();
    res.send(users);
  },
};
const models = require('../database/models/index'); // I tried also with destructuring

module.exports = {
  fetchAllUsers: async () => models.user.findAll(),
};

and my actual test file looks like我的实际测试文件看起来像

const request = require('supertest');

const SequelizeMock = require('sequelize-mock');
const app = require('..');

const dbMock = new SequelizeMock();
const models = require('../src/database/models/index');

jest.mock('../src/database/models/index', () => ({
  user: jest.fn(),
}));

models.user.mockImplementation(() => {
  const UserMock = dbMock.define('user', {});
  UserMock.$queueResult(UserMock.build({
    username: 'username',
    mail: 'myMail@myMail.com',
  }));
  return UserMock;
});

describe('Demo test', () => {
  it('should respond to users route', (done) => {
    request(app)
      .get('/users')
      .end((err, res) => {
        expect(err).toBeNull();
        expect(res.status).toBe(200);
        expect(res.json).toBe('object');
        done();
      });
  });
});


All of this is actually working but when I'm trying to mock the user I TypeError: models.user.findAll is not a function所有这些实际上都是有效的,但是当我试图模拟用户时,我TypeError: models.user.findAll is not a function

I need to replace the model.user with the UserMock's value.我需要用 UserMock 的值替换 model.user 。

Is there anyway to do this?有没有办法做到这一点? or I should just mock findAll like或者我应该像这样模拟 findAll

jest.mock('../src/database/models/index', () => ({
  user: () => ({ findAll: jest.fn() }),
}));

``

In this case, I was not mocking what I wanted to.在这种情况下,我不是我想要的 mocking。

If you wish to mock the models all you need to do is use SpyOn like如果您想模拟模型,您需要做的就是使用SpyOn类的

const { sequelize, Report, User } = require('../../database/models/index');


describe("my test", () => {
    it("should just mock", () => {
        jest.SpyOn(Report, "count").mockResolvedOnce(6);
    })
})

In the case that you need to mock like your service如果您需要模拟您的服务

first create jest functions to allow the access from outside the scope of your mock and then mock it with "double class call"首先创建 jest 函数以允许从模拟的 scope 外部访问,然后使用“双 class 调用”模拟它

const BaseService = require('../BaseService'); const BaseService = require('../BaseService'); const mockFecthOne = jest.fn();常量 mockFecthOne = jest.fn();


jest.mock('../BaseService',
  () => jest.fn().mockImplementation(
    () => ({
      fetchOne: mockFetchOne,
    }),
  ));

// inside your test just

BaseService().fetchOne.mockResolvedOnce({....})

and thats it hope it works.这就是它希望它的工作原理。

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

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