【问题标题】:Unit testing classes with expo sqlite calls in jest开玩笑的带有 expo sqlite 调用的单元测试类
【发布时间】:2018-03-14 00:21:20
【问题描述】:

在学习对我的 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 的嵌套函数中。

【问题讨论】:

    标签: javascript sqlite unit-testing jestjs expo


    【解决方案1】:

    能够通过一些想法来解决这个问题:

    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 调用的一些数据

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-15
      • 2017-10-01
      • 2018-09-10
      • 2021-02-05
      • 1970-01-01
      • 2016-03-03
      • 2020-08-16
      • 1970-01-01
      相关资源
      最近更新 更多