美文网首页
angular单元测试

angular单元测试

作者: nzjcnjzx | 来源:发表于2018-12-03 14:50 被阅读0次

常用断言方法

  • Jasmine 提供非常丰富的API,一些常用的Matchers:
toBe() 等同 ===
toNotBe() 等同 !==
toBeDefined() 等同 !== undefined
toBeUndefined() 等同 === undefined
toBeNull() 等同 === null
toBeTruthy() 等同 !!obj
toBeFalsy() 等同 !obj
toBeLessThan() 等同 <
toBeGreaterThan() 等同 >
toEqual() 相当于 ==
toNotEqual() 相当于 !=
toContain() 相当于 indexOf
toBeCloseTo() 数值比较时定义精度,先四舍五入后再比较。
toHaveBeenCalled() 检查function是否被调用过
toHaveBeenCalledWith() 检查传入参数是否被作为参数调用过
toMatch() 等同 new RegExp().test()
toNotMatch() 等同 !new RegExp().test()
toThrow() 检查function是否会抛出一个

而这些API之前用 not 来表示负值的判断。

expect(true).not.toBe(false);

angular cli使用karma进行单元测试.

  • 创建一个新的项目

ng new project --routing

  • 运行ng test --help 可以看到测试相关的执行参数
 options:
  --browsers
    Override which browsers tests are run against.
  --code-coverage
    Output a code coverage report.
  --code-coverage-exclude
    Globs to exclude from code coverage.
  --configuration (-c)
    A named configuration environment, as specified in the "configurations" section of angular.json.
  --environment
    Defines the build environment.
  --eval-source-map
    Output in-file eval sourcemaps.
  --help
    Shows a help message for this command in the console.
  --karma-config
    The name of the Karma configuration file.
  --main
    The name of the main entry-point file.
  --poll
    Enable and define the file watching poll time period in milliseconds.
  --polyfills
    The name of the polyfills file.
  --preserve-symlinks
    Do not use the real path when resolving modules.
  --prod
    When true, sets the build configuration to the production environment.
    All builds make use of bundling and limited tree-shaking, A production build also runs limited dead code elimination using UglifyJS.
  --progress
    Log progress to the console while building.
  --reporters
    Karma reporters to use. Directly passed to the karma runner.
  --source-map
    Output sourcemaps.
  --ts-config
    The name of the TypeScript configuration file.
  --vendor-source-map
    Resolve vendor packages sourcemaps.
  --watch
    Run build when files change.
image.png

NO_ERRORS_SCHEMA告诉angular忽略那些不识别的元素或者元素属性.

--code-coverage -cc 代码覆盖率报告, 默认这个是不开启的, 因为生成报告的速度还是比较慢的.
--colors 输出结果使用各种颜色 默认开启
--single-run -sr 执行测试, 但是不检测文件变化 默认不开启
--progress 把测试的过程输出到控制台 默认开启
--sourcemaps -sm 生成sourcemaps 默认开启
--watch -w 运行测试一次, 并且检测变化 默认开启
ng test 就是运行测试, 并且如果文件有变化, 就会重新运行测试.

使用ng test -sr或者ng test -w false 执行单次测试

下面生成代码覆盖率报告:

ng test -sr -cc

image.png

E2E测试的参数.

它的命令是 ng e2e.

常用的参数有:

--config -c 指定配置文件 默认是 protractor.conf.js
--element-explorer -ee 打开protractor的元素浏览器
--serve -s 在随机的端口编译和serve 默认true
--specs -sp 默认是执行所有的spec文件, 如果想执行某个spec就使用这个参数, 默认是all
--webdriver-update -wu 尝试更新webdriver 默认true

通常执行下面机组命令参数组合
ng e2e
ng e2e -ee

image.png

和单元测试类似,但是黑盒测试的一种, 注重的是从用户的角度出发,端对端的测试。

相关文章

网友评论

      本文标题:angular单元测试

      本文链接:https://www.haomeiwen.com/subject/eyuycqtx.html