Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  70] [ 2]  / answers: 1 / hits: 16348  / 4 Years ago, thu, september 10, 2020, 12:00:00

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.


More From » typescript

 Answers
22

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

[#50655] Friday, August 28, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hasancolec

Total Points: 603
Total Questions: 95
Total Answers: 98

Location: South Korea
Member since Sat, Oct 2, 2021
3 Years ago
;