4

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.

1 Answer 1

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')
Sign up to request clarification or add additional context in comments.

2 Comments

Looks like it works! I had implemented some other code that caused issues. Thank you for your answer!
Actually it's highly inefficient. If Expect returned a true or false boolean it could be wrapped into a custom framework method that would perform additional actions (highlight elements or text in red) based on the return value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.