使用Jest测试React商店

时间:2015-05-08 18:22:55

标签: unit-testing reactjs reactjs-flux jestjs

我正在尝试使用Jest测试我的React商店(我坚持使用Flux架构),但我不确定何时需要模拟商店功能。为了说明我的观点,这是我店铺代码的一部分:

export default class AdminStore extends EventEmitter {
   constructor() {
       super();
       this.users = [];
       this.userTotal = 0;
       this.profile = {};

       AdminDispatcher.register((payload) => {
           switch (payload.eventName) {
               case AdminConstants.USER_TOTAL:
                   this.userTotal = payload.total;
                   this.emit('change');
               break;

               case AdminConstants.ALL_USERS:
                   this.users = payload.users;
                   this.emit('change');
               break;

               case AdminConstants.FETCH_USER:
                   this.profile = payload.profile;
                   this.emit('change');
               break;

               default:

               break;
           }
           return true;
       });
   }

   syncUsers() {
       return this.users;
   }

   syncUserTotal() {
       return this.userTotal;
   }

   syncProfile() {
       return this.profile;
   }
}

以下是我的Jest测试代码的片段:

jest.dontMock('../AdminStore.js');
jest.dontMock('../../constants/AdminConstants.js');

describe('AdminStore', () => {
    let callback;
    let AdminStore;
    let AdminDispatcher;
    let AdminConstants = require('../../constants/AdminConstants.js');

    beforeEach(() => {
        AdminStore = require('../AdminStore.js');
        AdminDispatcher = require('../../dispatcher/AdminDispatcher.js');
        callback = AdminDispatcher.register.mock.calls[0];
    });
    it ('should initialize with a user total of 0', () => {
        let total = AdminStore.syncUserTotal();
        expect(total).toEqual(0);
    });
});

此测试的我的Jest输出如下所示:

● AdminStore › it should initialize with a user total of 0
  - TypeError: undefined is not a function
    at Spec.<anonymous> (/Users/seanchen/karma/admin-new/src/js/stores/__tests__/AdminStore-test.js:34:32)
    at jasmine.Block.execute (/Users/seanchen/karma/admin-new/node_modules/jest-cli/vendor/jasmine/jasmine-1.3.0.js:1065:17)
    at jasmine.Queue.next_ (/Users/seanchen/karma/admin-new/node_modules/jest-cli/vendor/jasmine/jasmine-1.3.0.js:2098:31)
    at null._onTimeout (/Users/seanchen/karma/admin-new/node_modules/jest-cli/vendor/jasmine/jasmine-1.3.0.js:2088:18)
1 test failed, 1 test passed (2 total)
Run time: 3.493s

AdminStore.syncUserTotal()是否需要被嘲笑?我真的不确定为什么它没有定义。

1 个答案:

答案 0 :(得分:0)

您没有AdminStore实例。

您的AdminStore正在导出类本身,而不是类的实例。

尝试类似

的内容
it ('should initialize with a user total of 0', () => {
    let adminStore = new AdminStore();
    let total = adminStore.syncUserTotal();
    expect(total).toEqual(0);
});