【问题标题】:Problem when mock class Using jest with constructor method模拟类使用带构造函数方法的玩笑时出现问题
【发布时间】:2021-10-20 04:27:08
【问题描述】:

我是使用 Jest 进行单元测试的新手。 这是我的 Account 类

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

这是我的帐户服务

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

这是我的 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('');
  });
});

但是当我运行它时,会出现错误

TypeError: Account is not a constructor

请教我如何修复它以及如何模拟帐户?感谢您的关注。

【问题讨论】:

  • Account 不是构造函数,它只是一个对象。您的测试替身需要与他们要替换的东西具有相同的界面 - 您可以使用例如返回对象的函数(不是箭头函数)。

标签: javascript node.js unit-testing mongoose jestjs


【解决方案1】:

Account 模型是一个类,但您将它模拟为一个对象。这是解决方案:

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

测试结果:

 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多