嘲笑一个带有构造函数参数的新对象创建

时间:2019-04-19 20:53:39

标签: typescript jestjs

我需要帮助new TableName(params).save()来模拟在Jest中创建新的Dynamoose对象。我有模拟TableName.query(hashkey).eq(myhashkey).exec()和类似查询的代码。但是我在处理带有参数的new构造函数时遇到了麻烦。有人可以指导如何在Jest中做到这一点吗?

非常感谢您的光临!

//Code that I want to mock
const tableName =await new TableName({
   hashkey,
   rangekey,
   ...moreItems,
}).save();

//Mock Object but this mocks TableName.save() rather than TableName(...).save(). mockModel creates a dictionary object to access the operations on the table and works for query/scan/get etc.
const saveFn = mockModel(
  'dummyTableName',
  'save',
  jest.fn(() => Promise.resolve(exampleTableRecord))
);

//Mock assertion fails
expect(saveFn).toHaveBeenCalled();

1 个答案:

答案 0 :(得分:0)

这是单元测试解决方案:

index.ts

import { TableName } from './TableName';

export async function main() {
  const hashkey = 'hashkey';
  const rangekey = 'rangekey';
  const moreItems = {};
  const tableName = await new TableName({
    hashkey,
    rangekey,
    ...moreItems
  }).save();
}

TableName.ts

export class TableName {
  constructor(opts) {}
  async save() {
    return this;
  }
}

index.spec.ts

import { main } from './';
import { TableName } from './TableName';

jest.mock('./TableName.ts', () => {
  const mTableName = {
    save: jest.fn().mockReturnThis()
  };
  return { TableName: jest.fn(() => mTableName) };
});

const tableName = new TableName({ hashKey: '123', rangekey: '321' });

describe('main', () => {
  test('should ', async () => {
    await main();
    expect(tableName.save).toBeCalledTimes(1);
  });
});

覆盖率100%的单元测试结果:

 PASS  src/stackoverflow/55767756/index.spec.ts (10.88s)
  main
    ✓ should  (6ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.114s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55767756