简体   繁体   English

如何模拟 sequelize db - Jest

[英]How to mock sequelize db - Jest

I'm trying to write unit test for my service file.I got this when i testing SequelizeAccessDeniedError: Access denied for user ''@'localhost' (using password: NO)我正在尝试为我的服务文件编写单元测试。当我测试SequelizeAccessDeniedError: Access denied for user ''@'localhost' (using password: NO)时,我得到了这个

According to my knowledge i think it is beacouse of wrong db mocking.据我所知,我认为这是因为错误的数据库模拟。

ProgramService.js程序服务.js

class ProgramService {

    constructor() {
        this.subsciberProgram = new SubsciberProgram()
    }
  async subscribeUser(data) {
    try {
        const { msisdn, userId, programId, uuid } = data;
       
        if ((await this.subsciberProgram.findBySubscriberId(userId, programId)).length) {
            throw ({code:500,message:'You have already subscribed'});
        }

        return await this.subsciberProgram.create(userId, programId);

    } catch (error) {
        throw error;
    }
}
}

test.spec.js测试规范.js

const ProgramsService = require('../src/services/program/programService')
const SubsciberProgram = require('../src/services/subscriberProgram/subsciberProgramService')
const programsService = new ProgramsService()
const subsciberProgram = new SubsciberProgram()
const db = require('./../src/models')

beforeAll(() => {
  db.sequelize.sync({ force: true }).then(() => { });

});

describe('Subscribe', () => {
  test('should return 200', async () => {
    jest.spyOn(subsciberProgram, 'findBySubscriberId').mockResolvedValueOnce(null);
    const rep = await programsService.subscribeUser(serviceRecord);

    expect(rep).toBeTruthy();
  });
});

在此处输入图片说明

------------------------------------------------------------------------- -------------------------------------------------- -----------------------

***** Update for slideshowp2 ******* *****更新幻灯片p2 *******

在此处输入图片说明

Unit test solution:单元测试解决方案:

ProgramService.js : ProgramService.js :

import { SubsciberProgram } from './SubsciberProgram';

export class ProgramService {
  subsciberProgram;
  constructor() {
    this.subsciberProgram = new SubsciberProgram();
  }
  async subscribeUser(data) {
    try {
      const { msisdn, userId, programId, uuid } = data;

      if ((await this.subsciberProgram.findBySubscriberId(userId, programId)).length) {
        throw { code: 500, message: 'You have already subscribed' };
      }

      return await this.subsciberProgram.create(userId, programId);
    } catch (error) {
      throw error;
    }
  }
}

SubsciberProgram.js : SubsciberProgram.js :

export class SubsciberProgram {
  async findBySubscriberId(userId, programId) {
    return [1, 2];
  }
  async create(userId, programId) {
    return { userId, programId };
  }
}

ProgramService.spec.js : ProgramService.spec.js :

import { ProgramService } from './ProgramService';
import { SubsciberProgram } from './SubsciberProgram';

jest.mock('./SubsciberProgram', () => {
  const mSubsciberProgram = { findBySubscriberId: jest.fn(), create: jest.fn() };
  return { SubsciberProgram: jest.fn(() => mSubsciberProgram) };
});

describe('64101015', () => {
  afterAll(() => {
    jest.resetAllMocks();
  });
  it('should pass', async () => {
    const subsciberProgram = new SubsciberProgram();
    subsciberProgram.findBySubscriberId.mockResolvedValueOnce([]);
    subsciberProgram.create.mockResolvedValueOnce('success');
    const programService = new ProgramService();
    const serviceRecord = { userId: 1, programId: 2 };
    const actual = await programService.subscribeUser(serviceRecord);
    expect(actual).toEqual('success');
    expect(subsciberProgram.findBySubscriberId).toBeCalledWith(1, 2);
    expect(subsciberProgram.create).toBeCalledWith(1, 2);
  });
});

unit test result with coverage report:带有覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/64101015/ProgramService.spec.js (14.337s)
  64101015
    ✓ should pass (10ms)

-------------------|----------|----------|----------|----------|-------------------|
File               |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-------------------|----------|----------|----------|----------|-------------------|
All files          |    77.78 |       50 |      100 |    77.78 |                   |
 ProgramService.js |    77.78 |       50 |      100 |    77.78 |             13,18 |
-------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        15.941s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM