我有一个简单的功能要用Jest测试。我已经读过https://jestjs.io/docs/en/mock-functions很多次了,但是我不确定出了什么问题,也找不到关于stackoverflow的明确答案。我觉得这是一个非常简单的测试。
这是我的功能:
public hello(name: string) {
return 'Hello ' + name
}
这是我的测试:
let hello = jest.fn()
jest.mock('./myfile.ts', () => {
return hello
})
beforeEach(() => {
hello('world')
})
describe('hello test', (){
it('expects to return concatenated string', () => {
expect(hello.mock.results[0].value).toBe('Hello world') // returns as undefined - Test fails
})
})
mock.results而不是“ Hello world”一直是未定义的。
我在做什么错?我觉得自己正在忽略一些非常简单的内容。
答案 0 :(得分:2)
您正在尝试模拟要测试的功能。您应该只嘲笑其他依赖项。
这就足够了:
expect(hello('world')).toBe('Hello world')