[英]Unit testing classes with expo sqlite calls in jest
Having trouble learning to unit test my expo/react-native app.在学习对我的 expo/react-native 应用程序进行单元测试时遇到问题。 How would I unit test adding transactions to the store in this class:
我将如何在此类中对向商店添加交易进行单元测试:
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);
}
}
All the callbacks within callbacks make this very difficult.回调中的所有回调都使这变得非常困难。 I guess I have to mock
db.transaction
somehow but I can't see how to do it in such a way to give a fake (tx, result)
into that nested function of executeSql
.我想我必须以某种方式模拟
db.transaction
但我不知道如何以这种方式将假(tx, result)
放入executeSql
嵌套函数中。
Was able to get this working with some thought:能够通过一些想法来解决这个问题:
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);
});
});
Talk about a brain workout!谈论大脑锻炼! This way I can manipulate
sqlResult
in between tests to fake some data from the sql calls这样我就可以在测试之间操作
sqlResult
来伪造来自 sql 调用的一些数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.