Home > Mobile >  Bunit - unit test downloading a file
Bunit - unit test downloading a file

Time:01-23

I am working a blazer web Assembly project. I want to write a unit test a download button, When I click the button, I can generate an agreement pdf.

private async Task generateServiceAgreement() { 
   var text = await planOfService.SavePlanOfService();   // from API      
    await JSRuntime.InvokeVoidAsync("BlazorDownloadFile", $"Service_Agreement.pdf", text);   // download the file using js function
}

Javascript function

function BlazorDownloadFile(filename, text) {
  let parser = new DOMParser();
  let doc = parser.parseFromString(text, "text/html");

  console.log(doc.body);
  const element = doc.body;

  var opt = {
    margin: 1,
    filename: filename,
    html2canvas: { scale: 4 },
    jsPDF: { unit: "cm", format: "a3", orientation: "portrait" },
    pagebreak: {
      mode: "",
      before: ".terms-and-conditions",
      avoid: [".agreement", ".terms-and-conditions"],
    },
  };
  html2pdf().set(opt).from(element).save();
}

How can I write a bunit test for this download function?

CodePudding user response:

You cannot test JavaScript with bUnit. bUnit is a testing library that sits on top of C# and runs just the C# portion of your Blazor components.

What you can test is that your Blazor components calls the expected JavaScript function, and thus assert that it uses your JavaScript as expected. In a bUnit test, we treat JavaScript like we would a web service during testing, i.e. by mocking/faking it.

Learn more here: https://bunit.dev/docs/test-doubles/emulating-ijsruntime

  • Related