【问题标题】:How to force Jest unit test assertion to execute before test ends?如何在测试结束之前强制执行 Jest 单元测试断言?
【发布时间】:2018-06-19 03:51:51
【问题描述】:

我的 react native 应用程序中有以下测试,但测试应该失败(因为返回的操作不等于我在 expectedActions 中输入的操作。我的猜测是它通过了,因为 expect 测试测试完成后运行。

如何强制测试等到 promise 完成并且期望测试运行?还有其他方法吗?

describe('authorize actions', () => {
    beforeEach(() => {
        store = mockStore({});
    });

    it('should create an action to signify successful auth', () => {
        auth.authorize.mockImplementation(() => Promise.resolve({"something": "value"}));
        const expectedActions = [{"type":"AUTHORIZE_RESPONSE","payload":{"something":"sdklfjsdf"}}];

        authorizeUser(store.dispatch, store.state).then(() => {
            expect(store.getActions()).toEqual(expectedActions);
        });

    })
});

【问题讨论】:

    标签: javascript reactjs unit-testing redux jestjs


    【解决方案1】:

    好的,看来我只是错过了一些 Jest 文档 - 如果您返回承诺,即 return auth.authorize.mockImplementation(() => Promise.resolve...,那么 Jest 将等到它完成后再继续。

    【讨论】:

      【解决方案2】:

      有多种测试异步代码的方法。查看文档以获取示例:https://facebook.github.io/jest/docs/en/asynchronous.html

      一个人可能会兑现承诺:

      describe('authorize actions', () => {
      beforeEach(() => {
          store = mockStore({});
      });
      
      it('should create an action to signify successful auth', () => {
          auth.authorize.mockImplementation(() => Promise.resolve({"something": "value"}));
          const expectedActions = [{"type":"AUTHORIZE_RESPONSE","payload":{"something":"sdklfjsdf"}}];
      
          return authorizeUser(store.dispatch, store.state).then(() => {
              expect(store.getActions()).toEqual(expectedActions);
          });
      
      })
      

      });

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-12
        • 2019-01-14
        • 2018-05-06
        • 2020-06-22
        • 1970-01-01
        • 2021-09-11
        • 1970-01-01
        • 2016-08-07
        相关资源
        最近更新 更多