我们如何模拟Redux异步操作的获取?

时间:2015-12-29 21:03:43

标签: javascript unit-testing reactjs redux nock

在Redux的Writing Tests部分中,store.dispatch(actions.fetchTodos())如果fetch字面上调用store.dispatchactions.fetchTodos如何不调用it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', (done) => { nock('http://example.com/') .get('/todos') .reply(200, { todos: ['do something'] }) const expectedActions = [ { type: types.FETCH_TODOS_REQUEST }, { type: types.FETCH_TODOS_SUCCESS, body: { todos: ['do something'] } } ] const store = mockStore({ todos: [] }, expectedActions, done) store.dispatch(actions.fetchTodos()) }) 方法?

    static X509Certificate2 GetCertificateFromStore(string thumbprint)
    {
        var store = new X509Store(StoreLocation.CurrentUser);

        try
        {
            thumbprint = Regex.Replace(thumbprint, @"[^\da-zA-z]", string.Empty).ToUpper();
            store.Open(OpenFlags.ReadOnly);

            var certCollection = store.Certificates;
            var currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
            var signingCert = currentCerts.Find(X509FindType.FindByThumbprint, thumbprint, false);

            if (signingCert.Count == 0)
            {
                throw new Exception($"Could not find Xero SSL certificate. cert_name={thumbprint}");
            }

            return signingCert[0];
        }
        finally
        {
            store.Close();
        }
    }

1 个答案:

答案 0 :(得分:2)

它正在调用fetch方法,但调用nock行:

nock('http://example.com/')
  .get('/todos')
  .reply(200, { todos: ['do something'] })

存根HTTP请求,以便fetch只返回正确的数据(实际上没有命中端点)。

另一种选择是将对fetch的调用提取到另一个模块 - 比如api - 并在您的操作创建者中使用它。在测试中,您只需在api模块上模拟适当的方法。