【发布时间】:2019-05-25 11:00:31
【问题描述】:
我需要测试使用 SerialPort 的代码。 开玩笑怎么办?我尝试模拟 SerialPort 并更改 write 方法实现:
protocol.js
import SerialPort from 'serialport'
const port = new SerialPort('/dev/ttyS0')
function getCRC(data) {
let crc = 0
for (let i = 0; i < data.length; i++) {
crc ^= data[i]
for (let j = 0; j < 8; j++) {
if (crc & 0x0001) crc = 0x08408 ^ crc >> 1
else crc >>>= 1
}
}
return Array.of(crc & 0xFF, crc >> 8 & 0xFF)
}
function reset() {
let msg = Array.of(0x02, 0x03, 0x06, 0x30)
msg = msg.concat(getCRC(msg))
port.write(msg)
}
export { reset }
protocol.spec.js
import { reset } from './protocol'
import SerialPort from 'serialport'
jest.mock('serialport')
describe('test protocol commands', () => {
beforeAll(() => {
SerialPort.mockImplementation(() => {
return {
write: () => {
throw new Error('test error')
}
}
})
})
it('should throw an error when calling reset command', () => {
expect(() => reset()).toThrow()
})
})
但它不起作用。如何正确更改实现?
【问题讨论】:
标签: javascript unit-testing jestjs node-serialport