如何用笑话嘲笑一个序列化事务



场景

我想要测试以下类型的函数。此功能具有

待测试文件

export const doSomething = () => {
sequelize.transaction(async t => {
customModel.upsert(dataObject, { transaction : t })

otherCustomModel.upsert(otherDataObject, { transaction : t })
})

}

这里,customModelotherCustomModel是在它们各自的文件中使用sequelize.define编写的有效模型。

这里sequelize

import Sequelize from 'sequelize';
const connectionParams = {
// assume valid config is present
}
const sequelize = new Sequelize(connectionParams);
(async () => {
try {
await sequelize.authenticate();
console.log('Sequelize authenticated successfully');
} catch (error) {
console.log(`Unable to connect to the database: ${error}`);
}
})();
export default sequelize;

要求

我想写一个带有以下检查的测试用例:

  1. 测试以下函数是否被调用一次。

    • transaction
    • customModel.upsert
    • otherCustomModel.upsert
  2. 整个功能执行

对于这样的函数,我如何使用jest来模拟序列化事务?


我的测试

test("text", () => {

// mocks
sequelize.transaction = jest.fn()
customModel.upsert = jest.fn()
otherCustomModel.upsert = jest.fn()

doSomething()
// assertions
expect(sequelize.transaction).toBeCalled();
expect(customModel.upsert).toBeCalled();
expect(otherCustomModel.upsert).toBeCalled();
})

面临错误

expect(jest.fn()).toBeCalled()
Expected number of calls: >= 1
Received number of calls:    0
62 |        expect(sequelize.transaction).toBeCalled();

版本

s编号
12

我会把它写成这样的

describe('doSomething', () => {
beforeAll(() => {
doSomething()
})
it('should call transaction with a callback', () => {
expect(sequalize.transaction).toHaveBeenCalledWith(
expect.any(Function)
)
})
describe('the transaction', () => {
let mockTransaction = { prop: 'dummy transaction object' }

beforeAll(() => {
const transactionCallback = sequalize.transaction.mock.calls[0][0]
transactionCallback(mockTransaction)
// presuming you're NOT using jest.spyOn on sequalize.transaction
// you have to call the callback passed to it
})
it('should have called customModel.upsert', () => {
const dataObject = expect.objectContaining({
// ...expected properties
})
expect(customModel.upsert).toHaveBeenCalledWith(
dataObject, { transaction : mockTransaction }
);
})
it.todo('should have called otherCustomModel.upsert ... same as above')
})
})

您应该能够做到这一点,例如:

const sequelize = require('sequelize');
const customModel = require('<your module>');
const otherCustomModel = require('<your module>');
jest.mock('sequelize', () => ({
transaction: jest.fn(() => jest.fn()),
}));
jest.spyOn(customModel, 'upsert');
jest.spyOn(otherCustomModel, 'upsert');

在您的测试用例中:

sequelize.transaction.mockImplementation(() => jest.fn());
otherCustomModel.upsert.mockImplementation(() => jest.fn());
customModel.upsert.mockImplementation(() => jest.fn());

然后你可以做你的断言,例如:

expect(sequelize.transaction).toBeCalled();

相关内容

  • 没有找到相关文章

最新更新