首页 > 解决方案 > 如何用打字稿开玩笑地模拟静态方法和实例

问题描述

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

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只是一个普通函数而不是一个开玩笑的模拟函数。

我尝试过的其他事情:

谢谢!

标签: typescriptjestjsmockingts-jest

解决方案


哦,我终于试过const mockRecord = new MockedRecord('bax') as jest.Mocked<Record>;了,它奏效了!


推荐阅读