Как смоделировать запрос на обслуживание с базой данных? - PullRequest
0 голосов
/ 02 ноября 2019

Я новичок в Jest и не понимаю, как смоделировать запрос к сервису для юнит-теста.

EmployeeController.js

const EmployeeService = require('../services/employeeService');

    exports.getEmployeeById = (req, res) => {
      EmployeeService.find(req.params.employeeId) // need to be mocked
        .then((employee) => {
          if (employee == 0 || '') {
            return res.status(404).json({
              success: false,
              message: 'Employee not found!'
            });
          } else {
            return res.status(200).json({
              success: true,
              employee: employee
            });
          }
        }).catch(err => {
          res.status(404).json({
            success: false,
            message: 'Employee not found!'
          });
        });
    }

EmployeeService.find - возвращает мне из базы данных объект сотрудника по введенному идентификатору в URL.

EmployeeService.js

const sql = require('../config/connection');
const Promise = require('bluebird');
const connection = require('../config/connection');
const Employee = require('../models/employee.model');

var queryAsync = Promise.promisify(connection.query.bind(connection));

Employee.find = async function (employeeId) {
  var result = queryAsync(
    "SELECT empID, empName, IF(empActive, 'Yes', 'No') empActive, dpName FROM Employee INNER JOIN Department ON empDepartment = dpID WHERE empID = ? ", employeeId);
  return result;
}

employee.model.js - модель сотрудника.

const Employee = function (emp) {
  this.empName = emp.empName;
  this.empActive = emp.empActive;
  this.empDepartment = emp.empDepartment;
  this.creator = emp.creator;
};
module.exports = Employee;

1 Ответ

0 голосов
/ 02 ноября 2019

Jest имеет встроенные утилиты для удаления зависимостей.

const employeeService = require("../services/employeeService");
const employeeController = require("./employeeController");
describe("employeeController", () => {
  beforeEach(() => {
    // this mock can be overridden wherever necessary, eg by using
    // employeeService.find.mockRejectedValue(new Error("oh no"));
    // by default, resolve with something that meets the needs of your consuming
    // code and fits the contract of the stubbed function
    jest.spyOn(employeeService, "find").mockResolvedValue(someMockQueryResult);
  });
  afterEach(() => {
    jest.restoreAllMocks();
  });
  // contrived test to show how jest stubs can be used
  it("fetches the employee", async () => {
    await employeeController.getEmployeeById(123);
    expect(employeeService.find).toHaveBeenCalledWith(123);
  });
});

Есть также опции для макетирования всего модуля. Проверьте шутливые документы:

https://jestjs.io/docs/en/mock-functions.html

https://jestjs.io/docs/en/manual-mocks.html

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...