typescript - 如何用打字稿开玩笑地模拟静态方法和实例
问题描述
我正在尝试使用打字稿在一个笑话测试中模拟一个静态方法和一个类的实例,但我不知道如何让它们都被模拟。这是一个代码示例:
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
只是一个普通函数而不是一个开玩笑的模拟函数。
我尝试过的其他事情:
- 明确地将模拟设置为 in
jest.mock('./record', () => {implementation})
,但后来我遇到了打字问题,因为模拟丢失了签名中的静态方法Record
- 使用
import { mocked } from 'ts-jest/utils';
andconst mockRecord = mocked(Record);
然后我遇到Property 'getId' does not exist on type 'MockedObject<typeof Record>'.
谢谢!
解决方案
哦,我终于试过const mockRecord = new MockedRecord('bax') as jest.Mocked<Record>;
了,它奏效了!
推荐阅读
- vue.js - vue 更改特定的 du/component 路由器路径
- jenkins - 如果分支条件不起作用,詹金斯声明性单管道
- xamarin.forms - 使用“html:HtmlLabel(xam.Plugin.HtmlLabel)”而不是 Label Xamarin Forms 时未触发 ItemSelected 事件
- hyperledger-fabric - 不同的 MSP 角色(成员、管理员、对等方、客户端)如何影响 Hyperledger Fabric 背书策略?
- soap - 带有数字的 WSDL 合同列表
- php - PHP 的 NumberFormatter 从哪里获取语言环境格式?
- android - 当在 RecyclerView 中通过滑动删除视图时不会在 SharedPreference 中删除
- angular - Angular Kendo UI 数据网格从服务中填充
- asp.net-mvc - 升级到 bootstrap 4 CSS minifier 在 asp.net mvc 中中断
- r - 使用 R 更改土耳其语文本中的特定字母