Problem when mock class Using jest with constructor method

I am a new with unit test using Jest. This is my Account class

....
const Account = mongoose.model('Account', AccountSchema);
module.exports = {
  Account,
};

This is my accountService

function createAccount(data) {
  const account = new Account(user_id: data.user_id);
}

This is my accountService.test

const { createAccount } = require('../../src/service/accountService')
const { Account } = require('../../src/models/Account');

jest.mock('../../src/models/Account', () => ({
  Account: {
    create: jest.fn(),
    findOne: jest.fn(),
    find: jest.fn(),
  }
}));

describe('Test function', () => {
  it('Run create account function', async () => {
    const result = await createAccount({
      user_id: 1,
    });
    expect(result).toEqual('');
  });
});

However when I run it, an error appears

TypeError: Account is not a constructor

Please teach me how to fix it and how to mock account ? Thank for your attention.

Upvotes: 0

Views: 227

Answers (1)

Lin Du
Lin Du

Reputation: 102257

Account model is a class, but you mocked it as an object. Here is the solution:

account.js:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const AccountSchema = new Schema({ name: String, user_id: Number });
const Account = mongoose.model('Account', AccountSchema);

module.exports = {
  Account,
};

accountService.js:

const { Account } = require('./account');

async function createAccount(data) {
  const account = new Account({ user_id: data.user_id });
  await account.save();
}

module.exports = { createAccount };

accountService.test.js:

const { createAccount } = require('./accountService');

const accountDocument = {
  save: jest.fn(),
  findOne: jest.fn(),
  find: jest.fn(),
};

jest.mock('./account', () => ({
  Account: jest.fn(() => accountDocument),
}));

describe('Test function', () => {
  it('Run create account function', async () => {
    await createAccount({ user_id: 1 });
    expect(accountDocument.save).toBeCalledTimes(1);
  });
});

test result:

 PASS  examples/68831298/accountService.test.js (9.378 s)
  Test function
    ✓ Run create account function (2 ms)

-------------------|---------|----------|---------|---------|-------------------
File               | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------------|---------|----------|---------|---------|-------------------
All files          |     100 |      100 |     100 |     100 |                   
 accountService.js |     100 |      100 |     100 |     100 |                   
-------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.339 s, estimated 12 s

Upvotes: 1

Related Questions