Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何使用Jest模拟服务对typescript中的控制器进行测试的响应_Node.js_Typescript_Unit Testing_Jestjs - Fatal编程技术网

Node.js 如何使用Jest模拟服务对typescript中的控制器进行测试的响应

Node.js 如何使用Jest模拟服务对typescript中的控制器进行测试的响应,node.js,typescript,unit-testing,jestjs,Node.js,Typescript,Unit Testing,Jestjs,我正在使用Jest测试一个用typescript编写的控制器。我试图模仿服务的响应,但没有成功 这是我的员工管理员 import { EmployeesService } from '../services/employeeService'; import { IDBConnection } from '../config/IDBConnection'; export class EmployeesController { private employeeService: Employee

我正在使用Jest测试一个用typescript编写的控制器。我试图模仿服务的响应,但没有成功

这是我的员工管理员

import { EmployeesService } from '../services/employeeService';
import { IDBConnection } from '../config/IDBConnection';

export class EmployeesController {
  private employeeService: EmployeesService;

  constructor(dbConnection: IDBConnection) {
    this.employeeService = new EmployeesService(dbConnection);
  }
  public async findAllEmployees(req: any, res: any) {
    const numPerPage = +req.query.pagesize;
    const page = +req.query.page;
    try {
      const count = await this.employeeService.findCount();
      const results = await this.employeeService.findAll(numPerPage, page);
      let totalEmployee = count[0].totalCount;
      if (totalEmployee === 0) {
        return res.status(404).json({
          success: false,
          message: 'Employee not found'
        });
      } else if (count && results) {
        return res.status(200).json({
          employees: results,
          maxEmployees: totalEmployee
        });
      };
    } catch {
      res.status(500).json({
        success: false,
        message: 'Server error'
      });
    };
  }
这是我的员工服务

import { IDBConnection } from '../config/IDBConnection';
export class EmployeesService {
  private connection: any;

  constructor(connection: IDBConnection) {
    this.connection = connection;
  }
  async findCount() {
    const results = await this.connection.execute('SELECT count(*) as totalCount FROM EmployeeDB.Employees');
    return results; // [ RowDataPacket { totalCount: 5 } ]
  }
}
我可以假设在测试中我的服务不正确地连接到它,但我不太确定。有人能帮我吗

这是我的雇员考试

jest.mock('../../../services/employeeService');

import { EmployeesController } from '../../../controllers/employeeController';
import { EmployeesService } from '../../../services/employeeService';

describe('Employees', () => {
   test('should get count of employees', async () => {
      const getCount = jest.spyOn(EmployeesService.prototype, "findCount")
         .mockImplementation(() => Promise.resolve([{totalCount: 5}]));
      const mockResp = () => {
         const res: any = {}
         res.status = jest.fn().mockReturnValue(res)
         res.json = jest.fn().mockReturnValue(res)
         return res
      }
      const mockReq = () => {
         const req: any = {}
         req.query = jest.fn().mockReturnValue(req);
         return req
      }
      const req = mockReq({
         pagesize: 1,
         page: 0
      });
      const res = mockResp();
      await EmployeesController.prototype.findAllEmployees(req, res);
      expect(getCount).toHaveBeenCalledTimes(1); // Received number of calls: 0
   }
}

以下是单元测试解决方案:

控制器/employeeController.ts

从“../services/employeeService”导入{EmployeesService};
从“../config/IDBConnection”导入{IDBConnection};
导出类EmployeesController{
私人雇员服务:雇员服务;
构造函数(dbConnection:IDBConnection){
this.employeeService=newemployeesservice(dbConnection);
}
公共异步findAllEmployees(req:any,res:any){
const numPerPage=+req.query.pagesize;
const page=+req.query.page;
试一试{
const count=wait this.employeeService.findCount();
const results=wait this.employeeService.findAll(numPerPage,第页);
让totalEmployee=count[0]。totalCount;
如果(totalEmployee==0){
返回res.status(404.json)({
成功:错,
消息:“未找到员工”,
});
}else if(计数和结果){
返回res.status(200).json({
雇员:结果,
maxEmployees:TotalEmployeer,
});
}
}抓住{
res.status(500).json({
成功:错,
消息:“服务器错误”,
});
}
}
}
服务/employeeService.ts

从“../config/IDBConnection”导入{IDBConnection};
出口类雇员服务{
私人连接:任何;
构造函数(连接:IDBConnection){
这个连接=连接;
}
异步findCount(){
const results=wait this.connection.execute('SELECT count(*)as totalCount FROM EmployeeDB.Employees');
返回结果;//[RowDataPacket{totalCount:5}]
}
异步findAll(numPerPage,第页){
返回[];
}
}
config/IDBConnection.ts

导出接口IDBConnection{}
Employee.test.ts

从“/controllers/employeeController”导入{employeescocontroller};
从“/services/employeeService”导入{EmployeesService};
笑话模拟('./服务/员工服务',()=>{
常量mEmployeesService={
findCount:jest.fn(),
findAll:jest.fn(),
};
返回{EmployeesService:jest.fn(()=>mEmployeesService)};
});
描述('员工',()=>{
之后(()=>{
jest.resetAllMocks();
});
test('should get count of employees',async()=>{
const mIDBConnection={};
const employeeService=新员工服务(MIDB连接);

(employeeService.findCount为jest.MockedFunction

以下是单元测试解决方案:

控制器/employeeController.ts

从“../services/employeeService”导入{EmployeesService};
从“../config/IDBConnection”导入{IDBConnection};
导出类EmployeesController{
私人雇员服务:雇员服务;
构造函数(dbConnection:IDBConnection){
this.employeeService=newemployeesservice(dbConnection);
}
公共异步findAllEmployees(req:any,res:any){
const numPerPage=+req.query.pagesize;
const page=+req.query.page;
试一试{
const count=wait this.employeeService.findCount();
const results=wait this.employeeService.findAll(numPerPage,第页);
让totalEmployee=count[0]。totalCount;
如果(totalEmployee==0){
返回res.status(404.json)({
成功:错,
消息:“未找到员工”,
});
}else if(计数和结果){
返回res.status(200).json({
雇员:结果,
maxEmployees:TotalEmployeer,
});
}
}抓住{
res.status(500).json({
成功:错,
消息:“服务器错误”,
});
}
}
}
服务/employeeService.ts

从“../config/IDBConnection”导入{IDBConnection};
出口类雇员服务{
私人连接:任何;
构造函数(连接:IDBConnection){
这个连接=连接;
}
异步findCount(){
const results=wait this.connection.execute('SELECT count(*)as totalCount FROM EmployeeDB.Employees');
返回结果;//[RowDataPacket{totalCount:5}]
}
异步findAll(numPerPage,第页){
返回[];
}
}
config/IDBConnection.ts

导出接口IDBConnection{}
Employee.test.ts

从“/controllers/employeeController”导入{employeescocontroller};
从“/services/employeeService”导入{EmployeesService};
笑话模拟('./服务/员工服务',()=>{
常量mEmployeesService={
findCount:jest.fn(),
findAll:jest.fn(),
};
返回{EmployeesService:jest.fn(()=>mEmployeesService)};
});
描述('员工',()=>{
之后(()=>{
jest.resetAllMocks();
});
test('should get count of employees',async()=>{
const mIDBConnection={};
const employeeService=新员工服务(MIDB连接);
(employeeService.findCount为jest.MockedFunction