如何将Ospec与Mithril javascript

时间:2019-02-20 09:48:48

标签: javascript unit-testing mithril.js

我正在尝试使用o.spec测试我的组件,但失败了。

“飞镖测试”的错误消息是:

tests/MyComponent.js:1
(function (exports, require, module, __filename, __dirname) { import MyComponent from "./src/mycomponent"
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:617:28)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Glob.<anonymous> (node_modules/mithril/ospec/bin/ospec:37:37)
error Command failed with exit code 1.

通过npm或yarn设置:

yarn add mithril@next webpack webpack-cli

编辑package.json:

{
  ...
  "name": "my-project",
  "scripts": {
      "start": "webpack src/index.js --output bin/app.js -d --watch",
      "build": "webpack src/index.js --output bin/app.js -p",
      "test": "ospec"
  }
}

index.html:

<!DOCTYPE html>
<body>
 <script src="bin/app.js"></script>
</body>

src / mycomponent.js:

//var m = require("mithril")
import m from "mithril"

//module.exports = {
export default {
  view: function(vnode) {
      return m("div",
          m("p", "Hello World")
      )
  }
}

src / index.js:

import m from "mithril"
import MyComponent from "./mycomponent"
//var m = require("mithril")
//var MyComponent = require("./mycomponent")

m.mount(document.body, MyComponent)

tests / MyComponent.js

import MyComponent from "./src/mycomponent"
//var MyComponent = require("./src/mycomponent")

o.spec("MyComponent", function() {
    o("returns a div", function() {
        var vnode = MyComponent.view()

        o(vnode.tag).equals("div")
        o(vnode.children.length).equals(1)
        o(vnode.children[0].tag).equals("p")
        o(vnode.children[0].children).equals("Hello world")
    })
})

1 个答案:

答案 0 :(得分:0)

您需要使用来模拟环境

global.window = require("mithril/test-utils/browserMock.js")();
global.document = window.document;

在测试中。

https://mithril.js.org/testing.html上查看更多信息