学习对我的 expo/react-native 应用程序进行单元测试时遇到问题。我将如何对向此类中的商店添加事务进行单元测试:
export default class TransactionsStore {
@observable _transactions = [];
constructor(rootStore) {
this.rootStore = rootStore;
}
@action addTransaction(t, db) {
db.transaction(tx => {
tx.executeSql(
'INSERT INTO transactions (categoryId, description, date, amount, currencyCode, isReported) VALUES (?,?,?,?,?,?);',
[t.category, t.description, t.date, t.amount, t.currency.code, t.report],
(tx, result) => { t.id = result.insertId; }
);
}, error => alert(error));
this.reloadTransactions(db);
}
}
回调中的所有回调使这变得非常困难。我想我必须以某种方式模拟 db.transaction
但我看不到如何以这种方式将假的 (tx, result)
放入嵌套的executeSql
的函数。
最佳答案
能够通过一些想法让这个工作:
var sqlResult = { insertId: 1, rows: { _array: [] } };
const tx = { executeSql: jest.fn((query, sub=[], func=()=>true) => func({}, sqlResult)) };
const db = { transaction: jest.fn((func) => func(tx)) };
const rootStore = { db: db } };
describe('TransactionsStore', () => {
const store = new TransactionsStore(rootStore);
it('mocks sql', () => {
expect(tx.executeSql.mock.calls.length).toBeGreaterThan(0);
});
});
谈论大脑锻炼!这样我就可以在测试之间操作 sqlResult
来伪造来自 sql 调用的一些数据
关于javascript - 在开 Jest 中使用 expo sqlite 调用单元测试类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46533818/