I am trying to load a Javascript file from within a Unit Test for a Swift Package I am working on and it is failing.
Here is what I have so far ...
The sample files are located in
MyPackage/Tests/MyPackageTests/Resources/Sample.js
Within the
Package.swift
I have added therecources
attribute to the.testTarget
as follows:
import PackageDescription
let package = Package(
name: "MyPackage",
products: [
.library(
name: "MyPackage",
targets: ["MyPackage"]),
],
dependencies: [],
targets: [
.target(
name: "MyPackage"
),
.testTarget(
name: "MyPackageTests",
dependencies: ["MyPackage"],
resources: [.process("Resources")] // <---- Here is where I declare the Resources
),
]
)
- In my test case I have the following code:
import XCTest
import JavaScriptCore
class JavaScriptCoreTest: XCTestCase {
func testParseJSFile() throws {
let testBundle = Bundle(for: type(of: self))
XCTAssertNotNil(testBundle)
let file = "Sample"
guard let url = testBundle.url(forResource: file, withExtension: "js") else {
fatalError("Unable to find resource \(file)") // <--- ERROR HERE
}
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(file) from bundle.")
}
let js = String(decoding: data, as: UTF8.self)
let ctx = JSContext()!
ctx.evaluateScript(js)
// Rest of test logic here
}
For some reason I keep getting nil
for the url
. Any thoughts on what I might be doing wrong here?
NOTE I did read this other answer on StackOverflow but it did not help me here.