javascript - 测试子类的方法

标签 javascript jestjs es6-class

我正在尝试测试类 A 的方法 X 调用导入的函数 Y。类 A 是类 B 的子类,应该模拟出来。

A 类看起来像这样:

const B = require('./B');
const { Y } = require('../util');
class A extends B {
  constructor() {
    super('/A');
    this.setCors('');
    this.app.post('', this.X.bind(this));
  }

  X(req, res) {
    Y();
  }
}

module.exports = A;

尝试测试(以下Jest Official Docs):

const A = require('../path/to/A');
const B = require('../path/to/B');
jest.mock('../path/to/B', () => {
  return jest.fn().mockImplementation(() => {
    return { setCors: jest.fn(), app: { post: jest.fn() } };
  });
});

test('method X calls function Y', () => {
  (new A()).X();
  expect(Y).toBeCalled();
});

这会产生关于 A 构造函数的错误 TypeError: Cannot read property 'bind' of undefined

也许有必要只模拟构造函数,但我不知道该怎么做。

最佳答案

解决方案如下:

文件夹结构:

.
├── A.spec.ts
├── A.ts
├── B.ts
└── util.ts

A.ts:

import B from './B';
import { Y } from './util';

export default class A extends B {
  constructor() {
    super('/A');
    this.setCors('');
    this.app.post('', this.X.bind(this));
  }

  public X(req, res) {
    Y();
  }
}

B.ts:

export default class B {
  public app = {
    post(route: string, controller: () => any) {
      //
    }
  };
  private name: string = '';
  private url: string = '';
  constructor(name: string) {
    this.name = name;
  }

  protected setCors(url: string) {
    this.url = url;
  }
}

util.ts:

export function Y() {
  console.log('I am Y');
}

A.spec.ts:

import A from './A';
import { Y } from './util';

jest.mock('./util.ts', () => {
  return {
    Y: jest.fn()
  };
});

const a = new A();

describe('A', () => {
  it('should execute function Y correctly', () => {
    const mockedReq = {};
    const mockedRes = {};
    a.X(mockedReq, mockedRes);
    expect(Y).toBeCalledTimes(1);
  });
});

单元测试结果与 100% 覆盖率报告:

PASS  src/stackoverflow/52075711/A.spec.ts (5.747s)
  A
    ✓ should execute function Y correctly (8ms)

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

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

关于javascript - 测试子类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52075711/

相关文章:

JavaScript 启动和停止计时

javascript - 在 Javascript 中,如果有一个对象有很多函数属性,你如何将它们转换为字符串数组(函数名称)?

javascript - 实例化并使用 2 个或更多 JavaScript ES6 类

javascript - 节点: prototype using "Class" syntax does not show expected object

javascript - React 组件中的故障加载方法

javascript改变字体大小和行间距遇到

javascript - 通过javascript更改整个文档的CSS值

javascript - 使用 jest fake 计时器测试 redux-saga debounce

javascript - React/Jest/Enzyme - 等待的时间不够长

reactjs - Jest 遇到意外标记,因为试图导入 Jest 无法解析的文件