【问题标题】:How to mock both static methods and instances in jest with typescript如何用打字稿开玩笑地模拟静态方法和实例
【发布时间】:2021-01-22 23:56:48
【问题描述】:

我正在尝试使用打字稿在一个笑话测试中模拟一个静态方法和一个类的实例,但我不知道如何让它们都被模拟。这是一个代码示例:

record.ts:

export default class Record {
  id: string;

  constructor(id : string) {
    this.id = id;
  }

  getId() : string {
    return this.id;
  }

  static getRecords() : Array<Record> {
    return [new Record('foo'), new Record('bar')]
  }
}

reader.ts:

import Record from './record';

export default class Reader {
  record: Record;
  constructor(record : Record) {
    this.record = record;
  }

  getRecordId() : string {
    return this.record.getId();
  }

  static getReaders() : Array<Reader> {
    return Record.getRecords().map((record) => new Reader(record))
  }
}

reader.test.ts:

import Reader from './reader'
import Record from './record'

jest.mock('./record');
const MockedRecord = Record as jest.Mocked<typeof Record>;
const mockRecord = new MockedRecord('bax');
MockedRecord.getRecords.mockImplementation(() => [mockRecord]);

describe('with getReaders', () => {
  it('returns the id of the associated records', () => {
    mockRecord.getId.mockImplementation(() => 'baz'); // This line fails because "Property 'mockImplementation' does not exist on type '() => string'"
    expect(Reader.getReaders()[0].getRecordId()).toEqual('baz')
  })
})

我在这里发现的问题是 mockRecord 没有被模拟,mockRecord.getId 只是一个普通函数而不是一个开玩笑的模拟函数。

我尝试过的其他事情:

  • 明确地将模拟设置为jest.mock('./record', () =&gt; {implementation}),但随后我遇到了打字问题,因为模拟丢失了Record 签名中的静态方法
  • 使用import { mocked } from 'ts-jest/utils';const mockRecord = mocked(Record); 然后我遇到Property 'getId' does not exist on type 'MockedObject&lt;typeof Record&gt;'.

谢谢!

【问题讨论】:

  • 请注意,Record 不是一个好的导入名称,因为它会干扰 TS 自己的 Record 类型。

标签: typescript jestjs mocking ts-jest


【解决方案1】:

哦,我终于尝试了const mockRecord = new MockedRecord('bax') as jest.Mocked&lt;Record&gt;;,它成功了!

【讨论】:

    猜你喜欢
    • 2018-10-29
    • 2021-06-26
    • 2019-07-09
    • 1970-01-01
    • 2019-02-06
    • 2019-03-23
    • 2021-10-09
    • 1970-01-01
    相关资源
    最近更新 更多