jest.mock
вызовы подняты на babel-jest
, поэтому эта строка запускается первой:
jest.mock('serialport')
..., которая автоматически моделирует модуль serialport
.
import
Далее следуют строки, поэтому protocol.js
импортируется ... и когда импортируется, эта строка запускается:
const port = new SerialPort('/dev/ttyS0')
..., которая создает port
с использованием пустой автоматической моделируемой реализации SerialPort
.
Затем запускается beforeAll
, который создает фиктивную реализацию для SerialPort
, но это не влияет на port
, созданный в protocol.js
, поскольку он уже создан.
Есть несколько способов исправить это.
Вы можете отложить создание port
до тех пор, пока оно не понадобится в reset
:
function reset() {
let msg = Array.of(0x02, 0x03, 0x06, 0x30)
msg = msg.concat(getCRC(msg))
const port = new SerialPort('/dev/ttyS0') // <= create port here
port.write(msg)
}
Вы можете использовать фабрику модулейфункция для создания макета:
import { reset } from './protocol'
jest.mock('serialport', () => {
class MockSerialPort {
write() {
throw new Error('test error')
}
}
return MockSerialPort;
});
describe('test protocol commands', () => {
it('should throw an error when calling reset command', () => {
expect(() => reset()).toThrow() // Success!
})
})
Или вы можете макет write
на prototype
из SerialPort
:
import { reset } from './protocol'
import SerialPort from 'serialport'
jest.mock('serialport')
describe('test protocol commands', () => {
beforeAll(() => {
const mock = jest.spyOn(SerialPort.prototype, 'write');
mock.mockImplementation(() => {
throw new Error('test error')
});
})
it('should throw an error when calling reset command', () => {
expect(() => reset()).toThrow() // Success!
})
})