【发布时间】: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', () => {implementation}),但随后我遇到了打字问题,因为模拟丢失了Record签名中的静态方法 - 使用
import { mocked } from 'ts-jest/utils';和const mockRecord = mocked(Record);然后我遇到Property 'getId' does not exist on type 'MockedObject<typeof Record>'.
谢谢!
【问题讨论】:
-
请注意,
Record不是一个好的导入名称,因为它会干扰 TS 自己的Record类型。
标签: typescript jestjs mocking ts-jest