代码之家  ›  专栏  ›  技术社区  ›  Sanjay

为什么测试脚本总是无法完成测试脚本的执行?JEST nodejs测试超时错误

  •  0
  • Sanjay  · 技术社区  · 5 年前

    我有一个非常简单的中间件可以使用jest进行测试。中间件使用mongoose-odm

    // auth.service.ts
    attachAutoUser = async (req, res, next) => {
    
        console.log('ATTACH SYSTEM USER ');
        console.log('emal:', req.globalconfig.AUTO_USER_EMAIL);
        let user = await User.findOne({ email: req.globalconfig.AUTO_USER_EMAIL }).select(`firstName lastName email role`).exec();
        console.log('user: ', user);
        
        return next();
      }
    

    我的测试脚本:

    // auth.service.test.ts
    import { Request, Response, NextFunction } from 'express';
    
    import AuthService from '../../../server/auth/auth.service';
    const auth = new AuthService();
    
    jest.setTimeout(30000);
    
    describe('AuthService', () => {
      
      // 
      describe('attachAutoUser middleware', () => {
        const mockRequest: any = {
          globalconfig: {
            AUTO_USER_EMAIL: 'test@abc.com'
          }
        };
        const mockResponse: any = {
          json: jest.fn()
        };
        const mockNext: NextFunction = jest.fn();
    
        it('should call next()', async () => {
          await auth.attachAutoUser(mockRequest, mockResponse, mockNext);
          expect(mockNext).toHaveBeenCalled();
        })
      })
    
    });
    
    

    $ npm test /tests/server/auth/auth1.service.test.ts -- --detectOpenHandles --runInBand --collectCoverage
    

    日志详细信息:

    ------------------------|---------|----------|---------|---------|------------------------------------------------------------------------------------------------------------------------
    File                    | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s                                                                                                      
    ------------------------|---------|----------|---------|---------|------------------------------------------------------------------------------------------------------------------------
    All files               |   24.79 |     9.09 |   10.99 |   24.84 |                                                                                                                        
     server                 |   57.14 |    80.49 |   42.86 |   57.14 |                                                                                                                        
      config.ts             |   47.62 |    80.49 |      25 |   47.62 | 77-94,175-181                                                                                                          
      server-stream.ts      |   85.71 |      100 |   66.67 |   85.71 | 6                                                                                                                      
     server/api             |   22.39 |        0 |    4.35 |   22.73 |                                                                                                                        
      base.ts               |   22.39 |        0 |    4.35 |   22.73 | 8-13,16-18,24-28,34-38,45-52,56-61,66-68,74-86,93-95,101-104,111,119-123,132                                           
     server/api/auditLog    |      40 |        0 |       0 |      40 |                                                                                                                        
      auditLog.model.ts     |      40 |        0 |       0 |      40 | 17-39                                                                                                                  
     server/api/funeralHome |     100 |      100 |     100 |     100 |                                                                                                                        
      funeralHome.model.ts  |     100 |      100 |     100 |     100 |                                                                                                                        
     server/api/role        |     100 |      100 |     100 |     100 |                                                                                                                        
      role.model.ts         |     100 |      100 |     100 |     100 |                                                                                                                        
     server/api/tenant      |   33.33 |        0 |       0 |   33.33 |                                                                                                                        
      tenant.model.ts       |   33.33 |        0 |       0 |   33.33 | 70-77,81-97                                                                                                            
     server/api/user        |   14.81 |        0 |       0 |   14.81 |                                                                                                                        
      user.model.ts         |   14.81 |        0 |       0 |   14.81 | 20-43,88-90,100-102,116-121,128-133,140-157,162,170-204,226-306                                                        
     server/auth            |    18.5 |        0 |    8.82 |   18.39 |                                                                                                                        
      auth.service.ts       |    18.5 |        0 |    8.82 |   18.39 | 33-44,51-69,72-80,86-88,93-245,257-283,295-318,330-365,380-393,402-418,431-474,482-600,608-611,620-623,628-636,644-649 
     server/version         |     100 |      100 |     100 |     100 |                                                                                                                        
      index.ts              |     100 |      100 |     100 |     100 |                                                                                                                        
    ------------------------|---------|----------|---------|---------|------------------------------------------------------------------------------------------------------------------------
    Test Suites: 1 failed, 1 total
    Tests:       1 failed, 1 total
    Snapshots:   0 total
    Time:        105.821 s
    

    连接自动用户中间件

    AuthService Attach自动用户中间件应调用next()

    : Timeout - Async callback was not invoked within the 100000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not
    

    jest.setTimeout.Error错误:

      20 |     const mockNext: NextFunction = jest.fn();
      21 | 
    > 22 |     it('should call next()', async () => {
         |     ^
      23 |       await auth.attachAutoUser(mockRequest, mockResponse, mockNext);
      24 |       expect(mockNext).toHaveBeenCalled();
      25 |     })
    

    修正: 正如Christian所指出的,我忘记了模拟/存根数据库调用。 这是一个固定的解决方案,以防其他人陷入类似的错误。

      describe('attachAutoUser middleware', () => {
        const mockRequest: any = {
          globalconfig: {
            AUTO_USER_EMAIL: 'test@abc.com'
          }
        };
        const mockResponse: any = {
          json: jest.fn()
        };
        const mockNext: NextFunction = jest.fn();
    
        it('should call next()', async () => {
          const UserFactory = {
            successResponse: {
              // user: 'the user OBJECT'
              user: {
                firstName: 'TestFirst',
                lastName: 'TestLast',
                email: 'test@abc.com',
                role: 'admin'
              }
            },
            failureResponse: {}
          };
    
          // User.findOne = jest.fn().mockImplementationOnce(() => ({
          //   select: jest.fn().mockResolvedValueOnce(UserFactory.successResponse)
          // }));
    
          User.findOne = jest.fn().mockImplementationOnce(() => ({
            select: jest.fn(() => ({
              exec: jest.fn().mockResolvedValueOnce(UserFactory.successResponse)
            }))
          }));
    
          await auth.attachAutoUser(mockRequest, mockResponse, mockNext);
          expect(mockNext).toHaveBeenCalled();
        });
      });
    
    0 回复  |  直到 5 年前
        1
  •  0
  •   Sanjay    5 年前

    忘记存根数据库调用。

    describe('attachAutoUser middleware', () => {
        const mockRequest: any = {
          globalconfig: {
            AUTO_USER_EMAIL: 'test@abc.com'
          }
        };
        const mockResponse: any = {
          json: jest.fn()
        };
        const mockNext: NextFunction = jest.fn();
    
        it('should call next()', async () => {
          const UserFactory = {
            successResponse: {
              // user: 'the user OBJECT'
              user: {
                firstName: 'TestFirst',
                lastName: 'TestLast',
                email: 'test@abc.com',
                role: 'admin'
              }
            },
            failureResponse: {}
          };
    
          User.findOne = jest.fn().mockImplementationOnce(() => ({
            select: jest.fn(() => ({
              exec: jest.fn().mockResolvedValueOnce(UserFactory.successResponse)
            }))
          }));