最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I test the returned value in Jest? - Stack Overflow

programmeradmin5浏览0评论

I have a simple function that I want to test with Jest. I have read many many times but I'm not sure whats going wrong and can't find a clear answer on 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'.

What am I doing wrong? I feel like I'm overlooking something very simple.

I have a simple function that I want to test with 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. 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'.

What am I doing wrong? I feel like I'm overlooking something very simple.

Share Improve this question edited Sep 13, 2020 at 11:15 skyboyer 23.7k7 gold badges62 silver badges71 bronze badges asked Sep 10, 2020 at 19:22 Aleksandr ChernovAleksandr Chernov 451 gold badge1 silver badge5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

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')
发布评论

评论列表(0)

  1. 暂无评论