如何模拟使用数据库服务的请求?

时间:2019-11-01 22:12:51

标签: javascript node.js jestjs

我是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中输入的ID从数据库向我返回雇员对象。

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 :(得分:0)

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