【问题标题】:Nestjs e2e testing with mocking mongoose modelNestjs e2e 测试与模拟猫鼬模型
【发布时间】:2019-09-30 22:24:54
【问题描述】:

我正在用 supertest 为我的 NestJS + mongoose 应用程序编写端到端测试。我可以模拟 find()delete() 等 mongoose api。 但是使用猫鼬save() api,对于代码this.CatModel(CatObject),模拟不起作用。我没有用于测试系统的 mongodb,所以我需要模拟它。

cat.e2e-spec.ts

describe('cat apis', () => {
    let app: INestApplication;

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

    app = module.createNestApplication();
      server = app.getHttpServer();
      await app.init();
    });

    it(`POST /cat `, async () => {
        return await request(server)
            .post('/cat')
            .send(newCatPayload)
            .set('Accept', 'application/json')
            .expect(201)
            .expect(({ body }) => {
                expect(body).toEqual(expectedResponse);
            });
    });
});

catModel.ts

export const mockCatModel = {
    find: (obj) => {
        return [catMock];
    },

    save : (cat) => {
        return cat;
    }
};

cat.service.ts

public async createCat(catObject: CreateCatDto, user): Promise<ICat> {
    const oCat = this.catModel(catObject);
    oCat.user = user;
    return await oCat.save();
}

this.catModel.find() 工作正常,但 this.catModel() 抛出错误: 'this.catModel is not a function'.

我在catModel.ts中试过,添加下面的函数,

function : (a) => {return a;}

但是没有用。如果有人知道如何模拟this.catModel(catObject),请提供帮助。

【问题讨论】:

  • 只是为了确定,您在 cat.e2e-spec.ts 代码中声明的 server 变量在哪里?

标签: mongoose jestjs e2e-testing nestjs supertest


【解决方案1】:

你可以试试。或者可以)

  let app: INestApplication;
  let testingModule: TestingModule;
  let spyService: CatsService;

  beforeEach(async () => {
    testingModule = await Test.createTestingModule({
      controllers: [CatsController],
      providers: [
        {
          provide: CatsService,
          useFactory: () => ({
            findAll: jest.fn((obj) => [catMock]),
            save: jest.fn((cat) => cat)
          }),
        },
      ],
    }).compile();

    spyService = testingModule.get(CatsService);

    app = testingModule.createNestApplication();
    await app.init();
  });

【讨论】:

    猜你喜欢
    • 2019-08-04
    • 2017-04-26
    • 2021-06-04
    • 2013-01-16
    • 2019-12-20
    • 2019-12-28
    • 2019-05-04
    • 2019-10-10
    • 2018-07-15
    相关资源
    最近更新 更多