【问题标题】:Create mockImplementation for es6 Class' Static Method in Jest在 Jest 中为 es6 类的静态方法创建 mockImplementation
【发布时间】:2020-03-23 12:15:59
【问题描述】:

我正在测试一个函数,该函数在其中调用来自(es6 类)控制器的静态方法,该控制器返回 API 获取的结果。因为我正在编写一个单元测试并且控制器有自己的测试,所以我想模拟(技术上是假的)类中的静态方法来给我不同类型的响应。

// Controller.js
class Controller {
  static async fetchResults() {} // the method I want to fake
}
// func.js - the function I am writing the test for
const func = async (ctx) => {
  const data = await Controller.fetchResults(ctx.req.url)

  if (containsErrors(data)) ... // do some logic

  return { ...data, ...otherStuff }
}

这种伪造static async fetchResults() 的尝试没有任何作用,并且测试尝试调用原始控制器的fetchResults 方法。

// func.test.js
describe('when data is successfuly fetched', () => {
  jest.mock('./Controller.js', () => jest.fn().mockImplementation(() => ({
    fetchResults: jest.fn(() => mockResponse),
  });

  it('returns correct information', async () => {
    expect(await func(context)).toEqual({ ...mockResponse, ...otherStuff });
  });
});

下一次尝试似乎在某种程度上模拟工作,但返回值是undefined 而不是{ ...mockResponse, ...otherStuff },这表明整个类都被模拟了,但由于它找不到fetchResultsstatic 方法而不是实例方法。

import Controller from './Controller.js'

describe('when data is successfuly fetched', () => {
  Controller.mockImplementation(jest.fn(() => ({
    fetchHotel: () => { ...mockResponse, ...otherStuff }
  })

  it('returns correct information', async () => {
    expect(await func(context)).toEqual({ ...mockResponse, ...otherStuff });
  });
});

【问题讨论】:

标签: javascript unit-testing mocking jestjs


【解决方案1】:

您可以使用jest.spyOn(object, methodName) 来执行此操作。

例如

controller.js:

export class Controller {
  static async fetchResults(url) {
    return { result: 'real result' };
  }
}

func.js:

import { Controller } from './controller';

const func = async (ctx) => {
  const data = await Controller.fetchResults(ctx.req.url);
  // do some logic
  return { ...data };
};

export { func };

func.test.js:

import { Controller } from './controller';
import { func } from './func';

describe('60776211', () => {
  it('should pass', async () => {
    const fetchResultsSpy = jest.spyOn(Controller, 'fetchResults').mockResolvedValueOnce({ result: 'fake data' });
    const ctx = { req: { url: 'example.com' } };
    const actual = await func(ctx);
    expect(actual).toEqual({ result: 'fake data' });
    fetchResultsSpy.mockRestore();
  });
});

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

 PASS  stackoverflow/60776211/func.test.ts
  60776211
    ✓ should pass (5ms)

---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------|---------|----------|---------|---------|-------------------
All files      |   91.67 |      100 |      75 |   88.89 |                   
 controller.ts |      80 |      100 |      50 |      75 | 3                 
 func.ts       |     100 |      100 |     100 |     100 |                   
---------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.922s, estimated 11s

【讨论】:

    猜你喜欢
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 2021-02-03
    相关资源
    最近更新 更多