node.js - 如何在Service构造函数中对Controller和模拟@InjectModel进行单元测试

标签 node.js unit-testing jestjs nestjs

我在对 Controller 进行单元测试时遇到问题,并收到错误消息“嵌套无法解决我的服务依赖性”。
为了获得最大的覆盖范围,我想对 Controller 和相应的服务进行单元测试,并希望模拟像 Mongoose 连接之类的外部依赖项。同样,我已经尝试了以下链接中提到的建议,但没有发现任何运气:
https://github.com/nestjs/nest/issues/194#issuecomment-342219043
请在下面找到我的代码:

export const deviceProviders = [
    {
        provide: 'devices',
        useFactory: (connection: Connection) => connection.model('devices', DeviceSchema),
        inject: ['DbConnectionToken'],
    },
];


export class DeviceService extends BaseService {
    constructor(@InjectModel('devices') private readonly _deviceModel: Model<Device>) {
        super();
    }

    async getDevices(group): Promise<any> {
        try {
            return await this._deviceModel.find({ Group: group }).exec();
        } catch (error) {
            return Promise.reject(error);
        }
    }
}


@Controller()
export class DeviceController {
    constructor(private readonly deviceService: DeviceService) {
    }

   @Get(':group')
   async getDevices(@Res() response, @Param('group') group): Promise<any> {
        try {
            const result = await this.deviceService.getDevices(group);
            return response.send(result);
        }
        catch (err) {
            return response.status(422).send(err);
        }
    }
}


@Module({
    imports: [MongooseModule.forFeature([{ name: 'devices', schema: DeviceSchema }])],
    controllers: [DeviceController],
    components: [DeviceService, ...deviceProviders],
})
export class DeviceModule { }
单元测试:
describe('DeviceController', () => {
    let deviceController: DeviceController;
    let deviceService: DeviceService;

    const response = {
        send: (body?: any) => { },
        status: (code: number) => response,
    };

    beforeEach(async () => {
        const module = await Test.createTestingModule({
            controllers: [DeviceController],
            components: [DeviceService, ...deviceProviders],
        }).compile();

        deviceService = module.get<DeviceService>(DeviceService);
        deviceController = module.get<DeviceController>(DeviceController);
    });

    describe('getDevices()', () => {
        it('should return an array of devices', async () => {
            const result = [{
                Group: 'group_abc',
                DeviceId: 'device_abc',
            },
            {
                Group: 'group_xyz',
                DeviceId: 'device_xyz',
            }];
            jest.spyOn(deviceService, 'getDevices').mockImplementation(() => result);

            expect(await deviceController.getDevices(response, null)).toBe(result);
        });
    });
});
当我在上面运行测试用例时,出现两个错误:

Nest can't resolve dependencies of the DeviceService (?). Please make sure that the argument at index [0] is available in the current context.

Cannot spyOn on a primitive value; undefined given

最佳答案

示例代码:

import { Test } from '@nestjs/testing';

import { getModelToken } from '@nestjs/mongoose';


describe('auth', () => {
  let deviceController: DeviceController;
  let deviceService: DeviceService;

  const mockRepository = {
    find() {
      return {};
    }
  };

  beforeAll(async () => {
    const module = await Test.createTestingModule({
      imports: [DeviceModule]
    })
      .overrideProvider(getModelToken('Auth'))
      .useValue(mockRepository)
      .compile();

    deviceService = module.get<DeviceService>(DeviceService);
  });

  // ...


});

关于node.js - 如何在Service构造函数中对Controller和模拟@InjectModel进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52878055/

相关文章:

javascript - 如何为带有服务的 Controller 编写单元测试

node.js - 清晰的手动模拟 Jest

javascript - 为什么有同步和异步模块的规范?

javascript - 如何踢用户 session ? [ Node .js]

unit-testing - 使 Logback 在 ERROR 级别的日志事件上抛出异常

unit-testing - Jacoco覆盖率报告,从覆盖范围中排除方法

node.js - -安装AWS CDK后bash : cdk: command not found ,

node.js - 如何开始使用 node-soap

javascript - 在 Jest 中测试嵌套的 promise

javascript - 如何使用 Jest 测试异步代码而不将其作为回调传递?