Return different values when mocking a variable
Why is my mocking not working ? I want to mock a npm ws module by returning different values each time.
Each call to readyState
should return a value in this order: 0, 0, and then 1 afterwards
it.only('should connect to a wss server once readyState is OPEN', () => {
// Given
jest.doMock('ws', () => jest.fn(() => ({
on: () => jest.fn().mockReturnThis(),
readyState: jest.fn()
.mockReturnValueOnce(0)
.mockReturnValueOnce(0)
.mockReturnValue(1)
})))
const 开发者_运维问答Module = new (require('./websocket'))()
// When
Module.start()
// Then
expect(Module.client).toBeDefined()
expect(Module.client.readyState).toBe(0)
expect(Module.client.readyState).toBe(0)
expect(Module.client.readyState).toBe(1)
expect(Module.client.readyState).toBe(1)
})
I get this error:
● Websocket service provider › should connect to a wss server once readyState is OPEN
expect(received).toBe(expected) // Object.is equality
Expected: 0
Received: [Function mockConstructor]
159 | // Then
160 | expect(Module.client).toBeDefined()
> 161 | expect(Module.client.readyState).toBe(0)
| ^
162 | expect(Module.client.readyState).toBe(0)
163 | expect(Module.client.readyState).toBe(1)
164 | expect(Module.client.readyState).toBe(1)
at Object.toBe (src/services/websocket.spec.js:161:38)
If I do this, it obviously returns 1 each time:
jest.doMock('ws', () => jest.fn(() => ({
on: () => jest.fn().mockReturnThis(),
readyState: 1
})))
精彩评论