首页 > 解决方案 > 测试保存ggplots

问题描述

我正在为 ggplots 创建一堆测试。我包括检查标签、输出对象是否为 ggplot 等内容。但我不知道如何测试绘图是否使用testthatand保存ggsave。你知道怎么做吗?

标签: runit-testingggplot2testthat

解决方案


这是一种基于文件大小进行测试的方法。如果文件不存在,则为 NA,如果确实存在,则应 > 0。

library(testthat)
library(ggplot2)

test_that("plot is saved to file", {
  file <- tempfile(fileext = ".png")
  expect_equal(file.size(file), NA_real_)
  
  plot <- ggplot(mtcars, aes(wt, mpg)) +
    geom_point()
  
  ggsave(file, plot, "png")
  
  expect_true(file.size(file) > 0)
  
  unlink(file)
})


推荐阅读