如何在 Jest 中测试返回值?

How do I test the returned value in Jest?

我想用 Jest 测试一个简单的函数。我已经阅读 https://jestjs.io/docs/en/mock-functions 很多次,但我不确定出了什么问题,也无法在 Whosebug 上找到明确的答案。我觉得这是一个非常简单的测试。

这是我的函数:

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' 未定义。

我做错了什么?我觉得我忽略了一些非常简单的事情。

您正在尝试模拟要测试的函数。您应该只模拟其他依赖项。

这就足够了:

expect(hello('world')).toBe('Hello world')