tests/testthat/test_S3_methods.R

context("Check summary.lm Function")

# generate data
n = 300
x1 = runif(n)
x2 = rnorm(n)
z = sample(1:6, n, replace = T)
y = 2 + runif(1, -1, 1) * x1 + runif(1, -1, 1) * x2 + rnorm(n)

# fit model
m = lm(y ~ x1 + x2)

test_that("new summary function plays nicely with old one", {
    
    expect_identical(
        summary(m),
        stats::summary.lm(m)
    )
    
    expect_identical(
        summary(m),
        stats::summary.lm(m)
    )
    
    expect_identical(
        summary(m, correlation = TRUE),
        stats::summary.lm(m, correlation = TRUE)
    )
        
    expect_identical(
        summary(m, symbolic.cor = TRUE),
        stats::summary.lm(m, symbolic.cor = TRUE)
    )
    
    expect_identical(
        summary(m, correlation = TRUE, symbolic.cor = TRUE),
        stats::summary.lm(m, correlation = TRUE, symbolic.cor = TRUE)
    )
    
    expect_output(print(summary(lm(y ~ -1))), regex = "No Coefficients")
    expect_error(summary(lm(y ~ -1), robust = T), regex = "intercept")
    expect_error(summary(lm(y ~ -1), cluster = z), regex = "intercept")
    
    # with weights
    mw = lm(y ~ x1, weights = z)
    
    expect_identical(
        summary(mw),
        stats::summary.lm(mw)
    )
    
    expect_warning(summary(mw, robust = T))
    expect_warning(summary(mw, cluster = z))
    
})


context("Check S3 methods")

test_that("elements of robustSE can be extracted", {
    
    s = summary(m, robust = T)
    v = vcov(s)
    expect_true(is.matrix(v))
    expect_true(nrow(v) == 3L)
    expect_true(ncol(v) == 3L)
    expect_true(det(v) > 0)
    expect_true(length(vcov(s, se = TRUE)) == 3L)
    expect_true(nrow(coef(s)) == 3L)
                
    s = summary(m, cluster = z)
    v = vcov(s)
    expect_true(is.matrix(v))
    expect_true(nrow(v) == 3L)
    expect_true(ncol(v) == 3L)
    expect_true(det(v) > 0)
    expect_true(length(vcov(s, se = TRUE)) == 3L)
    expect_true(nrow(coef(s)) == 3L)

})

test_that("print.robustSE works properly", {
    
    s = summary(m, robust = T)
    expect_output(print(s),
                  regexp = "Call.*Robust covariance.*Coefficients")
                
    s = summary(m, cluster = z)
    expect_output(print(s), 
                  regexp = "Call.*Cluster-robust.*Coefficients")

})
baruuum/jars documentation built on Nov. 3, 2019, 2:06 p.m.