【问题标题】:How to mock sequelize db - Jest如何模拟 sequelize db - Jest
【发布时间】:2021-01-13 23:13:04
【问题描述】:

我正在尝试为我的服务文件编写单元测试。我在测试时得到了这个 SequelizeAccessDeniedError: Access denied for user ''@'localhost' (using password: NO)

据我所知,我认为这是因为错误的数据库模拟。

ProgramService.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

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();
  });
});

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

***** 幻灯片p2更新 *******

【问题讨论】:

  • 请提供被测代码。否则,我们不知道应该模拟哪个对象
  • @slideshowp2 我已经更新了我的问题。请查找相关代码

标签: node.js unit-testing jestjs sequelize.js


【解决方案1】:

单元测试解决方案:

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:

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

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);
  });
});

带有覆盖率报告的单元测试结果:

 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

【讨论】:

  • 感谢您的解决方案。但我收到此错误TypeError: SubsciberProgram is not a constructor。你对此有任何想法吗?我已经用截图更新了我的问题
  • @Tje123 请仔细检查。无关代码上的临时 cmets
猜你喜欢
  • 2021-02-15
  • 1970-01-01
  • 2018-12-25
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多