简体   繁体   English

用Jest模拟测试

[英]Testing with Jest mock

I'm using the Flux design pattern in my application and I need to test that an Application Action emits on a given Store in the payload that a component sends. 我在应用程序中使用Flux设计模式,并且需要测试组件发送的有效负载中给定商店上发出的应用程序动作。

Using a Dispatcher I send a payload like the following: 使用分派器,我发送如下所示的有效负载:

dispatcher.dispatch({
  action: ACTION_NAME,
  foo: 'bar',
  emitOn: {
   store: SomeStore, // extends EventEmitter
   componentIds: ['Foo-Bar']
  }
}

The dispatcher is implemented like so (Not necessarily important) 调度程序是这样实现的(不一定重要)

Dispatcher.register((payload) => {
 Actions.call(payload);
 return true;
});

When the dispatcher calls an action the object Actions will call that action and when the action finishes it should call emit on the given store. 当调度程序calls动作时,对象“ Actions将调用该动作,当动作完成时,应在给定存储上调用“ emit ”。

My question is how do I test this in my application? 我的问题是如何在应用程序中对此进行测试? I want to know if it's possible to check that emit was called after an action finishes. 我想知道是否有可能检查emit被称为一个动作完成之后。

To finish an action this function is called Actions.finish(payload) 要完成一个动作,此功能称为Actions.finish(payload)

And if you're curious what finish looks like: 如果您很好奇, finish会是什么样子:

  finish(payload) {
    payload.emitOn.map(emitter => {
      var store = emitter.store;
      emitter.componentIds.map(id => {
        store.emit(id);
      });
    });
  }

My current testing code, but the Error is never thrown: 我当前的测试代码,但从未抛出该错误:

  jest.mock('./TestStore.js', () => {
    return function() {
      return {
        emit: () => {
          throw new Error('Test Error');
        }
      };
    };
  });

  let ACTION = 'Test-Action';
  let payload = {
    action: ACTION,
    emitOn: [{
      store: TestStore, // The store to emit on
      componentIds: ['Test-Id']
    }]
  };

  expect(() => {
    AppActions.finish(payload);
  }).toThrow(Error);

SO for anyone caring about how to test if a function is called you can spy on a function using jest.spyOn 因此,对于关心如何测试函数是否被调用的任何人,您都可以使用jest.spyOn监视该函数

I found this here Understanding Jest Mocks 我在这里找到了了解笑话的人

I changed my testing code (Much cleaner and the right approach to this kind of testing) 我更改了测试代码(更干净,更正确的测试方法)

  const emitMock = jest.spyOn(TestStore, 'emit');

  let ACTION = 'Test-Action';
  let payload = {
    action: ACTION,
    emitOn: [{
      store: TestStore, // The store to emit on
      componentIds: ['Test-Id']
    }]
  };

  AppActions.finish(payload);

  expect(emitMock).toHaveBeenCalledTimes(1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM