简体   繁体   English

如何在 Jest 中测试返回值?

[英]How do I test the returned value in Jest?

I have a simple function that I want to test with Jest.我有一个简单的功能,我想用 Jest 进行测试。 I have read https://jestjs.io/docs/en/mock-functions many many times but I'm not sure whats going wrong and can't find a clear answer on stackoverflow.我已经多次阅读https://jestjs.io/docs/en/mock-functions ,但我不确定出了什么问题,也无法在 stackoverflow 上找到明确的答案。 I feel like this is an extremely simple test.我觉得这是一个非常简单的测试。

Here is my function:这是我的功能:

public hello(name: string) {
  return 'Hello ' + name
}

Here is my Test:这是我的测试:

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
  })
})

I keep getting undefined for the mock.results instead of 'Hello world'.我一直为 mock.results 而不是 'Hello world' 定义未定义。

What am I doing wrong?我究竟做错了什么? I feel like I'm overlooking something very simple.我觉得我忽略了一些非常简单的事情。

You are trying to mock a function that you want to test.您正在尝试模拟要测试的函数。 You should only mock other dependencies.您应该只模拟其他依赖项。

This is sufficient:这足够了:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM