然后我将核心内部的HTTP类用作注入依赖项
export class Core {
public http: http
constructor(http: http) {
this.http = http
}
public async getUserDomainNameEntry(
username: string,
domainUrl: string,
): Promise<IDomainNameEntry | undefined> {
const response = await this.http.get(
`${domainUrl}/api/v1/dns/search/username/${username}`,
)
if (response.status === 404 || !response.ok) {
console.log(response)
return undefined
}
const dnsEntry: IDomainNameEntry = await response.json()
return dnsEntry
}
}
这是我的玩笑测试:
import { Core } from '.'
import http from '../http'
it('Domain Name Entry Test', async () => {
http.prototype.get = jest.fn(async (_url: string) =>
Promise.resolve({
ok: true,
status: 200,
json: async () => ({ name: 'javierhersan.stw', urls: [], ips: [] }),
} as Response),
)
const core = new Core(new http())
const domainNameEntry = await core.getUserDomainNameEntry(
'javierhersan.stw',
'http://localhost:3000',
)
expect(domainNameEntry).toBeDefined()
if (domainNameEntry) {
expect(domainNameEntry).toHaveProperty('name')
expect(domainNameEntry).toHaveProperty('urls')
expect(domainNameEntry).toHaveProperty('ips')
}
})
eRror
TypeError: fetch failed
3 |
4 | public async request(url: string, options: RequestInit): Promise<Response> {
> 5 | const response = await fetch(`${url}`, options)
| ^
6 | return response
7 | }
8 |
at http.request (src/http/index.ts:5:20)
at Core.getUserDomainNameEntry (src/core/index.ts:172:20)
at Object.<anonymous> (src/core/index.test.ts:116:27)
为什么我的模拟方法不覆盖我的HTTP获得原始方法。嘲笑对象方法并将其作为嘲笑的依赖性的最佳方法是什么?我已经测试过几种方法,并且不工作总是在调用原始Get方法,为什么?
您应该使用开玩笑的模拟来模拟您的HTTP类,而不是原型:
import { Core } from '.'
import http from '../http'
jest.mock('../http', () => {
return jest.fn().mockImplementation(() => {
return { ok: true }
})
})
,但我认为这不是一个很好的考验。 在单位测试中,您要孤立地测试组件。如果您要测试
Core
,则只需测试
Core
并模拟其具有的任何依赖项。在这种情况下
Http
。单独的单位测试将负责。
其他方法:在此测试中,我们不在乎内部做什么。我们只关心内部做什么以及它如何与
Http
。我们这样做我嘲笑您的
Core
Instance(不是班级)并检查Http
正确调用
Http
正确。
Core